import queue
import sys
import time
from time import sleep
import numpy as np
import pandas as pd
import os
import csv
import nibabel as nib
import argparse
import matplotlib.pyplot as plt
import pyqtgraph as pg
from openpyxl.packaging import workbook
from openpyxl.reader.excel import load_workbook
# import SimpleITK as sitk
# from show_mesh import showmsh
# from show_nii import open_itk_snap
# from show_cond import open_itk_snap_cond, process_anisotropy_type
# from tdcs_simulation import tdcs_run_simulation
# from mcx_simulation import show_src_vol, view_result, view_result_mask, from_csv_get_subject_coord, run_fn, run_fn_stage2
# import subprocess
# # import head_model
# import tdcs_optimize_el
# import tdcs_optimize_el_network

from pyqtgraph.Point import Point
import openpyxl
from openpyxl.utils.exceptions import InvalidFileException
from queue import Queue
from PyQt5 import QtCore, QtWidgets, Qt
from PyQt5.QtCore import QThread, pyqtSignal,QTimer,Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QLabel, QVBoxLayout, QWidget, QSlider, \
    QTreeWidgetItem, QFileDialog, QTreeWidget, QInputDialog, QTableWidgetItem
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from torch.utils.data.graph import traverse

from data_conversion_utils import data_converse
from mainwindow import Ui_MainWindow
from connect_dialog import Ui_dialog
from warning_t1 import Ui_dialog1
from warning_path import Ui_dialog2
from alternating_current_dialog import Ui_Dialog
from pulse_dialog import Ui_PULSE
from stimulation_time_dialog import Stimulation_Ui_Dialog

from stimulation_frequency_dialog import Frequency_Ui_Dialog
from irradiance_dialog import Irradiance_Ui_Dialog
from serial_utils import *

from build_light import light_MainWindow
from build_electrode import  electrode_MainWindow

from PyQt5.QtGui import *
from PyQt5.QtWidgets import QHeaderView

pg.setConfigOption('background', 'w')  # 设置背景为白色


global sec
global sec1
global sec2
data_queue = queue.Queue()
data_queue_read = queue.Queue()

#脑氧采集数据
BO_data1 = Queue(maxsize=5000)
BO_data2 = Queue(maxsize=5000)
BO_i1 = 0
BO_i2 = 0
#脑电采集数据
# EEG_data1 = Queue(maxsize=5000)
# EEG_data2 = Queue(maxsize=5000)
# EEG_data3 = Queue(maxsize=5000)
# EEG_data4 = Queue(maxsize=5000)
# EEG_data5 = Queue(maxsize=5000)
# EEG_data6 = Queue(maxsize=5000)
# EEG_data7 = Queue(maxsize=5000)
# EEG_data8 = Queue(maxsize=5000)
EEG_data = Queue()
EEG_data1 = Queue()
EEG_data2 = Queue()
EEG_data3 = Queue()
EEG_data4 = Queue()
EEG_data5 = Queue()
EEG_data6 = Queue()
EEG_data7 = Queue()
EEG_data8 = Queue()

EEG_i1 = 0
EEG_i2 = 0
EEG_i3 = 0
EEG_i4 = 0
EEG_i5 = 0
EEG_i6 = 0
EEG_i7 = 0
EEG_i8 = 0

# 初始化脑电数据
EEG_data_1 = np.zeros(1000, dtype=float)
EEG_data_2 = np.zeros(1000, dtype=float)
EEG_data_3 = np.zeros(1000, dtype=float)
EEG_data_4 = np.zeros(1000, dtype=float)
EEG_data_5 = np.zeros(1000, dtype=float)
EEG_data_6 = np.zeros(1000, dtype=float)
EEG_data_7 = np.zeros(1000, dtype=float)
EEG_data_8 = np.zeros(1000, dtype=float)

# 初始化阻抗数据
impedance_data_1 = np.zeros(1000, dtype=float)
impedance_data_2 = np.zeros(1000, dtype=float)
impedance_data_3 = np.zeros(1000, dtype=float)
impedance_data_4 = np.zeros(1000, dtype=float)
impedance_data_5 = np.zeros(1000, dtype=float)
impedance_data_6 = np.zeros(1000, dtype=float)
impedance_data_7 = np.zeros(1000, dtype=float)
impedance_data_8 = np.zeros(1000, dtype=float)


#阻抗采集数据
impedance_data1 = Queue()
impedance_data2 = Queue()
impedance_data3 = Queue()
impedance_data4 = Queue()
impedance_data5 = Queue()
impedance_data6 = Queue()
impedance_data7 = Queue()
impedance_data8 = Queue()

impedance_i1 = 0
impedance_i2 = 0
impedance_i3 = 0
impedance_i4 = 0
impedance_i5 = 0
impedance_i6 = 0
impedance_i7 = 0
impedance_i8 = 0
# global sec3
# global sec4

#脑电采集的指令
EEG_HANDSHAKE = [0xAA,0x55, 0x01, 0x06, 0x00, 0x00, 0x55]
EEG_COLLECT   = [0xAA,0x55, 0x01, 0x06, 0x00, 0x01, 0x55]
EEG_CLOSE     = [0xAA,0x55, 0x01, 0x06, 0x00, 0x04, 0x55]

#脑氧采集的指令
BRAIN_OXYGEN_HANDSHAKE     = [0xAA,0x55, 0x03, 0x02, 0x00, 0x01, 0x01, 0x55]
BRAIN_OXYGEN_COLLECT       = [0xAA,0x55, 0x03, 0x03, 0x01, 0x01, 0x01, 0x03, 0x55]
BRAIN_OXYGEN_COLLECTDATA   = [0xAA,0x55, 0x03, 0x02, 0x03, 0x01, 0x04, 0x55]
BRAIN_OXYGEN_CLOSE         = [0xAA,0x55, 0x03, 0x03, 0x02, 0x01, 0x00, 0x03, 0x55]
BRAIN_OXYGEN_RECALCULATION = [0xAA,0x55, 0x03, 0x02, 0x04, 0x01, 0x05, 0x55]

#tDCS模块的指令
TDCS_START =[0xAA,0x55,0x02,0x07,0x00,0x00,0x00,0x00,0x55]
TDCS_RUN = [0xAA,0x55,0x02,0x07,0x00,0x40,0x00,0x00,0x55]
# 模式切换
DIRECT_CURRENT = [0xAA,0x55,0x02,0x07,0x00,0x01,0x00,0x00,0x55]
ALTERNATING_CURRENT = [0xAA,0x55,0x02,0x07,0x00,0x01,0x00,0x01,0x55]
PULSE = [0xAA,0x55,0x02,0x07,0x00,0x01,0x00,0x02,0x55]
PSEUDO_STIMULUS = [0xAA,0x55,0x02,0x07,0x00,0x01,0x00,0x03,0x55]
RANDOM = [0xAA,0x55,0x02,0x07,0x00,0x01,0x00,0x04,0x55]

# 电流时间调节
CURRENT_INCREASE = [0xAA,0x55,0x02,0x07,0x00,0x02,0x00,0x00,0x55]
CURRENT_DECREASE = [0xAA,0x55,0x02,0x07,0x00,0x08,0x00,0x00,0x55]
TIME_INCREASE = [0xAA,0x55,0x02,0x07,0x00,0x04,0x00,0x00,0x55]
TIME_DECREASE = [0xAA,0x55,0x02,0x07,0x00,0x10,0x00,0x00,0x55]

# 光刺激模块
STIMULATION_OPEN = [0xAA,0x55,0x04,0x01,0x00,0x01,0x55]
STIMULATION_CLOSE = [0xAA,0x55,0x04,0x01,0x00,0x00,0x55]

# 时间设置
# STIMULATION_TIME5_SET = [0xAA,0x55,0x04,0x06,0x54,0x05,0x55]
# STIMULATION_TIME12_SET = [0xAA,0x55,0x04,0x06,0x54,0x0C,0x55]
# STIMULATION_TIME20_SET = [0xAA,0x55,0x04,0x06,0x54,0x14,0x55]
# 刺激频率设置
# STIMULATION1_FREQUENCY10_SET = [0xAA,0x55,0x04,0x06,0x1F,0x0A,0x55]
# STIMULATION1_FREQUENCY40_SET = [0xAA,0x55,0x04,0x06,0x1F,0x28,0x55]
# STIMULATION2_FREQUENCY10_SET = [0xAA,0x55,0x04,0x06,0x2F,0x0A,0x55]
# STIMULATION2_FREQUENCY40_SET = [0xAA,0x55,0x04,0x06,0x2F,0x28,0x55]

# 辐照度设置,待定
# IRRADIANCE_SET = [0xAA,0x55,0x04,0x06,0x1E,0x0A,0x55]


# 通道开启
CHANNEL_OPEN= [0xAA,0x55,0x04,0x06,0x0c,0x11,0x55]
CHANNEL_OPEN_1= [0xAA,0x55,0x04,0x06,0x0c,0x10,0x55]
CHANNEL_OPEN_2= [0xAA,0x55,0x04,0x06,0x0c,0x01,0x55]


STIMULATION_RUN = [0xAA,0x55,0x04,0x02,0x00,0x01,0x55]
STIMULATION_STOP = [0xAA,0x55,0x04,0x02,0x00,0x02,0x55]
STIMULATION_RESET = [0xAA,0x55,0x04,0x02,0x00,0x03,0x55]

#软件首页
create_head={'subject_name':'', 'T1_path':'','T2_path':'','dMRI_path':'','head_models_folder':''}
headModule_path=''

#优化配置
config_parameters={'name':'','output_path':'','optional_goal':'','partition_input':'','ICA_input':'','TargetDot':'','AvoidDot':'','max_total_current':'','max_individual_current':'','max_active_electrodes':'','target_image_in_mni':'','target_intensity':'','target_dot_in_mni':'','avoid_dot_in_mni':''}
dot_flag="靶点"
subject_MNI=""
class connect_Dialog(QMainWindow, Ui_dialog):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
# class alternating_current_dialog(QMainWindow,Ui_Dialog):
class alternating_current_dialog(QWidget, Ui_Dialog):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
class pulse_dialog(QWidget,Ui_PULSE):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

class build_light(QMainWindow,light_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)



class build_electrode(QMainWindow,electrode_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
#创建头部模型弹窗提示
class warning_t1(QMainWindow, Ui_dialog1):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
class warning_path(QMainWindow, Ui_dialog2):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

# class stimulation_time_dialog(QMainWindow,Stimulation_Ui_Dialog):
#     def __init__(self):
#         super().__init__()
#         self.setupUi(self)
#
# class stimulation_frequency_dialog(QMainWindow,Frequency_Ui_Dialog):
#     def __init__(self):
#         super().__init__()
#         self.setupUi(self)
#
# class irradiance_dialog(QMainWindow,Irradiance_Ui_Dialog):
#     def __init__(self):
#         super().__init__()
#         self.setupUi(self)

#硬件进程
class SerialReadThread(QThread):
    def __init__(self, ser=None):
        super().__init__()
        self.ser = ser

    def run(self):
        global data_queue
        while True:
            if self.ser is not None and self.ser.inWaiting():
                # start_time = time.time()
                data = self.ser.read(4)
                if data.hex() == 'aa550106':
                    data += self.ser.read(3)
                elif data.hex() == '55aa0123':
                    # start_time2 = time.time()  # 记录循环开始的时间
                    data += self.ser.read(32)
                    # end_time2 = time.time()  # 记录循环结束的时间
                    # print(f"获取数据所用的时间: {end_time2 - start_time2:.9f} 秒")  # 打印所用时间
                elif data.hex()[:6] == 'aa5503':
                    number = int(data.hex()[6:8], 16) + 2
                    data += self.ser.read(number)

                # 刺激模块
                elif data.hex() == 'aa550207':
                    data += self.ser.read(5)
                elif data.hex() == 'aa550208':
                    data += self.ser.read(5)
                elif data.hex() == 'aa550401':
                    data += self.ser.read(3)
                elif data.hex() == 'aa550402':
                    data += self.ser.read(3)
                elif data.hex() == 'aa550406':
                    data += self.ser.read(3)
                else:
                 # while data.hex()[-2:] != 'aa' and data.hex()[-4:] != '0155':
                 while data.hex()[-2:] != 'aa':
                         data += self.ser.read(1)


                data_queue.put(data)
                # end_time = time.time()  # 记录循环结束的时间
                # print(f"获取数据所用的时间: {end_time - start_time:.9f} 秒")  # 打印所用时间

#脑电绘图线程
class EEGCollectThread(QThread):
    EEG_collect_signal = pyqtSignal(name='EEG_collect_data1')
    def __init__(self):
        super().__init__()

    def run(self):
        # time.sleep(1)  # 防止直接进循环, 阻塞主ui
        while True:
            global EEG_i1
            if not EEG_data1.empty():
                if EEG_i1 < 1000:
                    EEG_data_1[EEG_i1] = EEG_data1.get()
                    EEG_i1 = EEG_i1 + 1
                else:
                    EEG_data_1[:-1] = EEG_data_1[1:]
                    EEG_data_1[EEG_i1 - 1] = EEG_data1.get()
            global EEG_i2
            if not EEG_data2.empty():
                if EEG_i2 < 1000:
                    EEG_data_2[EEG_i2] = EEG_data2.get()
                    EEG_i2 = EEG_i2 + 1
                else:
                    EEG_data_2[:-1] = EEG_data_2[1:]
                    EEG_data_2[EEG_i2 - 1] = EEG_data2.get()
            global EEG_i3
            if not EEG_data3.empty():
                if EEG_i3 < 1000:
                    EEG_data_3[EEG_i3] = EEG_data3.get()
                    EEG_i3 = EEG_i3 + 1
                else:
                    EEG_data_3[:-1] = EEG_data_3[1:]
                    EEG_data_3[EEG_i3 - 1] = EEG_data3.get()
            global EEG_i4
            if not EEG_data4.empty():
                if EEG_i4 < 1000:
                    EEG_data_4[EEG_i4] = EEG_data4.get()
                    EEG_i4 = EEG_i4 + 1
                else:
                    EEG_data_4[:-1] = EEG_data_4[1:]
                    EEG_data_4[EEG_i4 - 1] = EEG_data4.get()
            global EEG_i5
            if not EEG_data5.empty():
                if EEG_i5 < 1000:
                    EEG_data_5[EEG_i5] = EEG_data5.get()
                    EEG_i5 = EEG_i5 + 1
                else:
                    EEG_data_5[:-1] = EEG_data_5[1:]
                    EEG_data_5[EEG_i5 - 1] = EEG_data5.get()
            global EEG_i6
            if not EEG_data6.empty():
                if EEG_i6 < 1000:
                    EEG_data_6[EEG_i6] = EEG_data6.get()
                    EEG_i6 = EEG_i6 + 1
                else:
                    EEG_data_6[:-1] = EEG_data_6[1:]
                    EEG_data_6[EEG_i6 - 1] = EEG_data6.get()
            global EEG_i7
            if not EEG_data7.empty():
                if EEG_i7 < 1000:
                    EEG_data_7[EEG_i7] = EEG_data7.get()
                    EEG_i7 = EEG_i7 + 1
                else:
                    EEG_data_7[:-1] = EEG_data_7[1:]
                    EEG_data_7[EEG_i7 - 1] = EEG_data7.get()
            global EEG_i8
            if not EEG_data8.empty():
                if EEG_i8 < 1000:
                    EEG_data_8[EEG_i8] = EEG_data8.get()
                    EEG_i8 = EEG_i8 + 1
                else:
                    EEG_data_8[:-1] = EEG_data_8[1:]
                    EEG_data_8[EEG_i8 - 1] = EEG_data8.get()
                # self.EEG_collect_signal.emit()

#阻抗绘图线程
class impedanceCollectThread(QThread):
    impedance_collect_signal = pyqtSignal(name='impedance_collect_data1')
    def __init__(self):
        super().__init__()

    def run(self):
        # time.sleep(1)  # 防止直接进循环, 阻塞主ui
        while True:
            global impedance_i1
            if not impedance_data1.empty():
                if impedance_i1 < 1000:
                    impedance_data_1[impedance_i1] = impedance_data1.get()
                    impedance_i1 = impedance_i1 + 1
                else:
                    impedance_data_1[:-1] = impedance_data_1[1:]
                    impedance_data_1[impedance_i1 - 1] = impedance_data1.get()
            global impedance_i2
            if not impedance_data2.empty():
                if impedance_i2 < 1000:
                    impedance_data_2[impedance_i2] = impedance_data2.get()
                    impedance_i2 = impedance_i2 + 1
                else:
                    impedance_data_2[:-1] = impedance_data_2[1:]
                    impedance_data_2[impedance_i2 - 1] = impedance_data2.get()
            global impedance_i3
            if not impedance_data3.empty():
                if impedance_i3 < 1000:
                    impedance_data_3[impedance_i3] = impedance_data3.get()
                    impedance_i3 = impedance_i3 + 1
                else:
                    impedance_data_3[:-1] = impedance_data_3[1:]
                    impedance_data_3[impedance_i3 - 1] = impedance_data3.get()
            global impedance_i4
            if not impedance_data4.empty():
                if impedance_i4 < 1000:
                    impedance_data_4[impedance_i4] = impedance_data4.get()
                    impedance_i4 = impedance_i4 + 1
                else:
                    impedance_data_4[:-1] = impedance_data_4[1:]
                    impedance_data_4[impedance_i4 - 1] = impedance_data4.get()
            global impedance_i5
            if not impedance_data5.empty():
                if impedance_i5 < 1000:
                    impedance_data_5[impedance_i5] = impedance_data5.get()
                    impedance_i5 = impedance_i5 + 1
                else:
                    impedance_data_5[:-1] = impedance_data_5[1:]
                    impedance_data_5[impedance_i5 - 1] = impedance_data5.get()
            global impedance_i6
            if not impedance_data6.empty():
                if impedance_i6 < 1000:
                    impedance_data_6[impedance_i6] = impedance_data6.get()
                    impedance_i6 = impedance_i6 + 1
                else:
                    impedance_data_6[:-1] = impedance_data_6[1:]
                    impedance_data_6[impedance_i6 - 1] = impedance_data6.get()
            global impedance_i7
            if not impedance_data7.empty():
                if impedance_i7 < 1000:
                    impedance_data_7[impedance_i7] = impedance_data7.get()
                    impedance_i7 = impedance_i7 + 1
                else:
                    impedance_data_7[:-1] = impedance_data_7[1:]
                    impedance_data_7[impedance_i7 - 1] = impedance_data7.get()
            global impedance_i8
            if not impedance_data8.empty():
                if impedance_i8 < 1000:
                    impedance_data_8[impedance_i8] = impedance_data8.get()
                    impedance_i8 = impedance_i8 + 1
                else:
                    impedance_data_8[:-1] = impedance_data_8[1:]
                    impedance_data_8[impedance_i8 - 1] = impedance_data8.get()
                # self.impedance_collect_signal.emit()


class SerialHandleThread(QThread):
    EEG_handshake_signal = pyqtSignal(name='serial_data')
    brain_oxygen_handshake_signal = pyqtSignal(name='serial_data2')
    brain_oxygen_collect_signal = pyqtSignal(name='serial_data3')
    brain_oxygen_discollect_signal = pyqtSignal(name='serial_data4')
    tDCS_start_signal = pyqtSignal(name='serial_data5')
    tDCS_error_signal = pyqtSignal(name='serial_data6')
    tDCS_run_signal = pyqtSignal(name='serial_data14')
    tDCS_stop_signal = pyqtSignal(name='serial_data15')
    stimulation_run_signal = pyqtSignal(name='serial_data7')
    stimulation_stop_signal = pyqtSignal(name='serial_data8')
    stimulation_reset_signal = pyqtSignal(name='serial_data9')
    stimulation_run1_signal = pyqtSignal(name='serial_data10')
    stimulation_run2_signal = pyqtSignal(name='serial_data11')
    stimulation_run12_signal = pyqtSignal(name='serial_data12')
    stimulation_run0_signal = pyqtSignal(name='serial_data13')
    def __init__(self):
        super().__init__()

    def run(self):
        time.sleep(1)  # 防止直接进循环, 阻塞主ui
        print('reading')
        global data_queue
        global BO_data1
        global BO_data2

        global EEG_data1
        global EEG_data2
        global EEG_data3
        global EEG_data4
        global EEG_data5
        global EEG_data6
        global EEG_data7
        global EEG_data8

        global impedance_data1
        global impedance_data2
        global impedance_data3
        global impedance_data4
        global impedance_data5
        global impedance_data6
        global impedance_data7
        global impedance_data8

        while True:
            while not data_queue.empty():
                start_time = time.time()  # 记录循环开始的时间
                data = data_queue.get()
                # for i in range(3):
                #     data += data_queue.get()
                # if data.hex() == 'aa550106':
                #     for i in range(3):
                #         data += data_queue.get()
                # elif data.hex() == '55aa0123':
                #     start_time2 = time.time()  # 记录循环开始的时间
                #     for i in range(32):
                #         data += data_queue.get()
                #     end_time2 = time.time()  # 记录循环结束的时间
                #     print(f"获取数据所用的时间: {end_time2 - start_time2:.9f} 秒")  # 打印所用时间
                # elif data.hex()[:6] == 'aa5503':
                #     number = int(data.hex()[6:8], 16) + 2
                #     for i in range(number):
                #         data += data_queue.get()
                #
                # # 刺激模块
                # elif data.hex() == 'aa550207':
                #     for i in range(5):
                #         data += data_queue.get()
                # elif data.hex() == 'aa550208':
                #     for i in range(5):
                #         data += data_queue.get()
                # elif data.hex() == 'aa550401':
                #     for i in range(3):
                #         data += data_queue.get()
                # elif data.hex() == 'aa550402':
                #     for i in range(3):
                #         data += data_queue.get()
                # elif data.hex() == 'aa550406':
                #     for i in range(3):
                #         data += data_queue.get()
                #
                # # 脑电采集时有缺失的数据
                # else:
                #     while data.hex()[-2:] != 'aa' and data.hex()[-4:] != '0155':
                #         data += data_queue.get()

                print(data.hex())
                data_hex = data.hex()
                #采集模块
                if data_hex[:12] == '55aa01230001':
                    data1 = data_converse(data_hex[22:28])
                    data2 = data_converse(data_hex[28:34])
                    data3 = data_converse(data_hex[34:40])
                    data4 = data_converse(data_hex[40:46])
                    data5 = data_converse(data_hex[46:52])
                    data6 = data_converse(data_hex[52:58])
                    data7 = data_converse(data_hex[58:64])
                    data8 = data_converse(data_hex[64:70])

                    global EEG_i1
                    if EEG_i1 < 1000:
                        EEG_data_1[EEG_i1] = data1
                        EEG_data_2[EEG_i1] = data2
                        EEG_data_3[EEG_i1] = data3
                        EEG_data_4[EEG_i1] = data4
                        EEG_data_5[EEG_i1] = data5
                        EEG_data_6[EEG_i1] = data6
                        EEG_data_7[EEG_i1] = data7
                        EEG_data_8[EEG_i1] = data8
                        EEG_i1 = EEG_i1 + 1
                    else:
                        EEG_data_1[:-1] = EEG_data_1[1:]
                        EEG_data_2[:-1] = EEG_data_2[1:]
                        EEG_data_3[:-1] = EEG_data_3[1:]
                        EEG_data_4[:-1] = EEG_data_4[1:]
                        EEG_data_5[:-1] = EEG_data_5[1:]
                        EEG_data_6[:-1] = EEG_data_6[1:]
                        EEG_data_7[:-1] = EEG_data_7[1:]
                        EEG_data_8[:-1] = EEG_data_8[1:]
                        EEG_data_1[EEG_i1 - 1] = data1
                        EEG_data_2[EEG_i1 - 1] = data2
                        EEG_data_3[EEG_i1 - 1] = data3
                        EEG_data_4[EEG_i1 - 1] = data4
                        EEG_data_5[EEG_i1 - 1] = data5
                        EEG_data_6[EEG_i1 - 1] = data6
                        EEG_data_7[EEG_i1 - 1] = data7
                        EEG_data_8[EEG_i1 - 1] = data8



                    # eeg_data_array = [data1, data2, data3, data4, data5, data6, data7, data8]
                    # EEG_data.put(eeg_data_array)
                    # EEG_data1.put(data1)
                    # EEG_data2.put(data2)
                    # EEG_data3.put(data3)
                    # EEG_data4.put(data4)
                    # EEG_data5.put(data5)
                    # EEG_data6.put(data6)
                    # EEG_data7.put(data7)
                    # EEG_data8.put(data8)
                    # print('脑电数据1：', data1)
                    # print('脑电数据2：', data2)
                    # print('脑电数据3：', data3)
                    # print('脑电数据4：', data4)
                    # print('脑电数据5：', data5)
                    # print('脑电数据6：', data6)
                    # print('脑电数据7：', data7)
                    # print('脑电数据8：', data8)
                elif data_hex[:12] == '55aa01230006':
                    data1 = int(data_hex[22:24], 16)
                    data2 = int(data_hex[28:30], 16)
                    data3 = int(data_hex[34:36], 16)
                    data4 = int(data_hex[40:42], 16)
                    data5 = int(data_hex[46:48], 16)
                    data6 = int(data_hex[52:54], 16)
                    data7 = int(data_hex[58:60], 16)
                    data8 = int(data_hex[64:66], 16)

                    global impedance_i1
                    if impedance_i1 < 1000:
                        impedance_data_1[impedance_i1] = data1
                        impedance_data_2[impedance_i1] = data2
                        impedance_data_3[impedance_i1] = data3
                        impedance_data_4[impedance_i1] = data4
                        impedance_data_5[impedance_i1] = data5
                        impedance_data_6[impedance_i1] = data6
                        impedance_data_7[impedance_i1] = data7
                        impedance_data_8[impedance_i1] = data8
                        impedance_i1 = impedance_i1 + 1
                    else:
                        impedance_data_1[:-1] = impedance_data_1[1:]
                        impedance_data_2[:-1] = impedance_data_2[1:]
                        impedance_data_3[:-1] = impedance_data_3[1:]
                        impedance_data_4[:-1] = impedance_data_4[1:]
                        impedance_data_5[:-1] = impedance_data_5[1:]
                        impedance_data_6[:-1] = impedance_data_6[1:]
                        impedance_data_7[:-1] = impedance_data_7[1:]
                        impedance_data_8[:-1] = impedance_data_8[1:]
                        impedance_data_1[impedance_i1 - 1] = data1
                        impedance_data_2[impedance_i1 - 1] = data2
                        impedance_data_3[impedance_i1 - 1] = data3
                        impedance_data_4[impedance_i1 - 1] = data4
                        impedance_data_5[impedance_i1 - 1] = data5
                        impedance_data_6[impedance_i1 - 1] = data6
                        impedance_data_7[impedance_i1 - 1] = data7
                        impedance_data_8[impedance_i1 - 1] = data8

                    # impedance_data1.put(data1)
                    # impedance_data2.put(data2)
                    # impedance_data3.put(data3)
                    # impedance_data4.put(data4)
                    # impedance_data5.put(data5)
                    # impedance_data6.put(data6)
                    # impedance_data7.put(data7)
                    # impedance_data8.put(data8)
                    # print('阻抗数据1：', data1)
                    # print('阻抗数据2：', data2)
                    # print('阻抗数据3：', data3)
                    # print('阻抗数据4：', data4)
                    # print('阻抗数据5：', data5)
                    # print('阻抗数据6：', data6)
                    # print('阻抗数据7：', data7)
                    # print('阻抗数据8：', data8)
                elif data_hex == 'aa550106070155':
                    self.EEG_handshake_signal.emit()
                elif data_hex[:12] == 'aa5503260002':
                    self.brain_oxygen_handshake_signal.emit()
                elif data_hex == 'aa5503030102010455':
                    self.brain_oxygen_collect_signal.emit()
                elif data_hex == 'aa5503030202000455':
                    self.brain_oxygen_discollect_signal.emit()
                elif data_hex[:12] == 'aa55033a0302':
                    data1 = int(data_hex[12:14], 16)
                    data2 = int(data_hex[14:16], 16)
                    if data1 >= 240:
                        print('脑氧数据1无效')
                    else:
                        BO_data1.put(data1)
                        print('脑氧数据1：', data1)
                    if data2 >= 240:
                        print('脑氧数据2无效')
                    else:
                        BO_data2.put(data2)
                        print('脑氧数据2：', data2)


                #刺激模块
                elif data_hex == 'aa5502071111111155':
                    self.tDCS_start_signal.emit()
                elif data_hex == 'aa5502072222222255':
                    self.tDCS_error_signal.emit()
                elif data_hex == 'aa5502070040010055':
                    self.tDCS_run_signal.emit()
                elif data_hex == 'aa5502070040020055':
                    self.tDCS_stop_signal.emit()
                elif data_hex == 'aa550402010155':
                    self.stimulation_run_signal.emit()
                elif data_hex == 'aa550402010255':
                    self.stimulation_stop_signal.emit()
                elif data_hex == 'aa550402010355':
                    self.stimulation_reset_signal.emit()
                elif data_hex == 'aa5504060c1f55':
                    self.stimulation_run1_signal.emit()
                elif data_hex == 'aa5504060cf155':
                    self.stimulation_run2_signal.emit()
                elif data_hex == 'aa5504060c1155':
                    self.stimulation_run12_signal.emit()
                elif data_hex == 'aa5504060cff55':
                    self.stimulation_run0_signal.emit()

                end_time = time.time()  # 记录循环结束的时间
                print(f"循环一次所用的时间: {end_time - start_time:.9f} 秒")  # 打印所用时间




            # time.sleep(0.1)







class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.connect_dialog = connect_Dialog()
        self.warning_t1 = warning_t1()
        self.warning_path = warning_path()
        self.alternating_current_dialog = alternating_current_dialog()
        self.pulse_dialog = pulse_dialog()
        # self.stimulation_time_dialog = stimulation_time_dialog()
        # self.stimulation_frequency_dialog = stimulation_frequency_dialog()
        self.build_light = build_light()
        self.build_electrode = build_electrode()
        self.treeWidget = QTreeWidget()
        #初始化脑氧数据
        self.BO_data_1 = np.zeros(20, dtype=float)
        self.BO_data_2 = np.zeros(20, dtype=float)

        # 初始化脑电数据
        self.EEG_data_1 = np.zeros(1000, dtype=float)
        self.EEG_data_2 = np.zeros(1000, dtype=float)
        self.EEG_data_3 = np.zeros(1000, dtype=float)
        self.EEG_data_4 = np.zeros(1000, dtype=float)
        self.EEG_data_5 = np.zeros(1000, dtype=float)
        self.EEG_data_6 = np.zeros(1000, dtype=float)
        self.EEG_data_7 = np.zeros(1000, dtype=float)
        self.EEG_data_8 = np.zeros(1000, dtype=float)
        # 初始化阻抗数据
        self.impedance_data_1 = np.zeros(1000, dtype=float)
        self.impedance_data_2 = np.zeros(1000, dtype=float)
        self.impedance_data_3 = np.zeros(1000, dtype=float)
        self.impedance_data_4 = np.zeros(1000, dtype=float)
        self.impedance_data_5 = np.zeros(1000, dtype=float)
        self.impedance_data_6 = np.zeros(1000, dtype=float)
        self.impedance_data_7 = np.zeros(1000, dtype=float)
        self.impedance_data_8 = np.zeros(1000, dtype=float)
        # 实例化秒计数器
        self.timer = QTimer()
        self.timer1 = QTimer()
        self.timer2 = QTimer()

        self.BO_data_1_timer = QTimer()
        self.BO_data_2_timer = QTimer()

        self.EEG_data_timer = QTimer()


        self.impedance_data_timer = QTimer()

        global sec
        sec = 0
        global sec1
        sec1 = 0
        global sec2
        sec2 = 0

        self.current_port = None
        self.initialize_ui()
        self.serial_read_thread = SerialReadThread(self.current_port)
        self.EEG_collect_thread =  EEGCollectThread()
        self.impedance_collect_thread = impedanceCollectThread()
        self.serial_handle_thread = SerialHandleThread()
        self.timer.timeout.connect(self.set_time)
        self.timer1.timeout.connect(self.set_time1)
        self.timer2.timeout.connect(self.set_time2)
        self.BO_data_1_timer.timeout.connect(self.BO_plotData1)
        self.BO_data_2_timer.timeout.connect(self.BO_plotData2)

        self.EEG_data_timer.timeout.connect(self.EEG_plotData2)

        self.impedance_data_timer.timeout.connect(self.impedance_plotData2)

        self.connect_dialog.confirm_btn.clicked.connect(self.back_confirm)
        self.connect_dialog.cancel_btn.clicked.connect(self.back_cancel)

        self.alternating_current_dialog.confirm_btn.clicked.connect(self.confirm_alternating_current)
        self.pulse_dialog.confirm_btn.clicked.connect(self.confirm_pulse)
        self.alternating_current_dialog.cancel_btn.clicked.connect((self.cancel_alternating_current))
        self.pulse_dialog.cancel_btn.clicked.connect(self.cancel_pulse)
        #
        # self.stimulation_time_dialog.confirm_btn.clicked.connect(self.confirm_stimulation_time)
        # self.stimulation_time_dialog.cancel_btn.clicked.connect(self.cancel_stimalation_time)

        # self.EEG_collect_thread.EEG_collect_signal.connect(self.EEG_plotData2)
        # self.impedance_collect_thread.impedance_collect_signal.connect(self.impedance_plotData2)

        self.serial_handle_thread.EEG_handshake_signal.connect(self.EEG_connect)
        self.serial_handle_thread.brain_oxygen_handshake_signal.connect(self.brain_oxygen_connect)
        self.serial_handle_thread.brain_oxygen_collect_signal.connect(self.brain_oxygen_collect)
        self.serial_handle_thread.brain_oxygen_discollect_signal.connect(self.brain_oxygen_discollect)
        self.serial_handle_thread.tDCS_start_signal.connect(self.tDCS_start)
        self.serial_handle_thread.tDCS_error_signal.connect(self.tDCS_error)
        self.serial_handle_thread.tDCS_run_signal.connect(self.tDCS_run)
        self.serial_handle_thread.tDCS_stop_signal.connect(self.tDCS_stop)

        self.serial_handle_thread.stimulation_run_signal.connect(self.prompt_stimulation_run)
        self.serial_handle_thread.stimulation_stop_signal.connect(self.prompt_simulation_stop)
        self.serial_handle_thread.stimulation_reset_signal.connect(self.reset_stimulation_parameter)
        self.serial_handle_thread.stimulation_run1_signal.connect(self.prompt_stimulation_run)
        self.serial_handle_thread.stimulation_run2_signal.connect(self.prompt_stimulation_run)
        self.serial_handle_thread.stimulation_run12_signal.connect(self.prompt_stimulation_run)
        self.serial_handle_thread.stimulation_run0_signal.connect(self.prompt_stimulation_run)

        self.build_light.buttonBox.rejected.connect(self.close_light_and_return)
        self.build_light.buttonBox.accepted.connect(self.writeToExcelsheet2)
        self.build_electrode.buttonBox.rejected.connect(self.close_electrode_and_return)
        self.build_electrode.buttonBox.accepted.connect(self.writeToExcelsheet1)
        self.warning_t1.btn_1.clicked.connect(self.back_OK1)
        self.warning_path.pushButton.clicked.connect(self.back_OK2)

    def initialize_ui(self):
        print('initialize_ui')
        available_ports = []#get_ports()
        if available_ports == []:
            print('暂无可用串口！')
            available_ports = ['COM1','COM2','COM3','COM4','COM5','COM6']
        for port in available_ports:
            self.connect_dialog.comboBox.addItem(port)




        self.ui.tabWidget.setStyleSheet("QTabWidget#tabWidget{background-color:rgb(255,0,0);}\
                                 QTabBar::tab{width:250px;height:40px;font:13pt;background-color:rgb(255, 255, 255);color:rgb(0, 127, 255);border:1px solid rgb(0, 127, 255)}\
                                 QTabBar::tab::selected{background-color:rgb(0, 127, 255);color:rgb(255,255,255)}")
        self.ui.label.setStyleSheet("color: rgb(0, 191, 255);")
        self.ui.tabWidget.setCurrentIndex(0)
        self.ui.stackedWidget.setCurrentIndex(0)
        self.ui.next_btn.clicked.connect(self.next)
        self.ui.pre_btn.clicked.connect(self.previous)
        self.ui.connect_btn.clicked.connect(self.open_port)
        self.ui.close_btn.clicked.connect(self.close_port)
        self.ui.EEG_collect_btn.clicked.connect(self.collect_EEG)
        self.ui.EEG_close_btn.clicked.connect(self.discollect_EEG)
        self.ui.BO_collect_btn.clicked.connect(self.collect_BO)
        self.ui.BO_close_btn.clicked.connect(self.discollect_BO)

        # 定义一个函数来生成颜色块图标
        def create_color_block_icon(color, size=20):
            pixmap = QPixmap(size, size)
            pixmap.fill(color)  # 用指定的颜色填充像素图
            icon = QIcon(pixmap)
            return icon

        red_icon = create_color_block_icon(QColor(255, 0, 0))
        green_icon = create_color_block_icon(QColor(0, 255, 0))
        blue_icon = create_color_block_icon(QColor(0, 0, 255))
        yellow_icon = create_color_block_icon(QColor(255, 255, 0))
        magenta_icon = create_color_block_icon(QColor(255, 0, 255))
        orange_icon = create_color_block_icon(QColor(255, 165, 0))  # 近似橙色
        purple_icon = create_color_block_icon(QColor(128, 0, 128))  # 一种紫色
        cyan_icon = create_color_block_icon(QColor(0, 255, 255))

        # 绘制脑氧数据图例
        BO_t1 = self.ui.tableWidget
        # 均匀拉伸
        # BO_t1.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # BO_t1.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)

        BO_data_lable1 = QTableWidgetItem("脑氧数据1 = 0.0")
        BO_data_lable1.setIcon(red_icon)
        BO_data_lable2 = QTableWidgetItem("脑氧数据2 = 0.0")
        BO_data_lable2.setIcon(green_icon)

        BO_t1.setItem(0, 0, BO_data_lable1)
        BO_t1.setItem(0, 1, BO_data_lable2)

        # 绘制脑氧数据波形
        p1 = self.ui.BO_display1.addPlot(title="脑氧数据波形")
        p1.showGrid(x=True, y=True)  # 把X和Y的表格打开
        p1.setRange(xRange=[0, 20], padding=0)
        # p1.setLabel(axis='bottom', text='x ')
        vLine = pg.InfiniteLine(angle=90, movable=False)
        hLine = pg.InfiniteLine(angle=0, movable=False)
        p1.addItem(vLine, ignoreBounds=True)
        p1.addItem(hLine, ignoreBounds=True)
        def mouseMoved(evt):
            pos = evt  # 获取鼠标位置
            if p1.sceneBoundingRect().contains(pos):
                vLine.show()
                hLine.show()
                mousePoint = p1.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
                index = int(mousePoint.x())
                if index >= 0 and index < len(self.BO_data_1):
                    p1.setLabel(axis='bottom', text="x=%0.1f y=%0.1f" % (
                        mousePoint.x(),mousePoint.y()))
                    BO_data_lable1.setText("脑氧数据1 = " + f"{self.BO_data_1[index]:.1f}")
                    BO_data_lable2.setText("脑氧数据2 = " + f"{self.BO_data_2[index]:.1f}")
                vLine.setPos(mousePoint.x())  # 设置垂直线的位置
                hLine.setPos(mousePoint.y())  # 设置水平线的位置
            else:
                vLine.hide()
                hLine.hide()
        p1.scene().sigMouseMoved.connect(mouseMoved)  # 监听鼠标移动事件
        self.curve1 = p1.plot(pen='r')  # 绘制一个图形
        self.curve1.setData(self.BO_data_1)
        self.curve2 = p1.plot(pen='g')  # 绘制一个图形
        self.curve2.setData(self.BO_data_2)

        # p2 = self.ui.BO_display2.addPlot(title="脑氧数据2波形")
        # p2.showGrid(x=True, y=True)  # 把X和Y的表格打开
        # p2.setRange(xRange=[0, 20], padding=0)
        # # p2.setLabel(axis='bottom', text='x ')
        # vLine2 = pg.InfiniteLine(angle=90, movable=False)
        # hLine2 = pg.InfiniteLine(angle=0, movable=False)
        # p2.addItem(vLine2, ignoreBounds=True)
        # p2.addItem(hLine2, ignoreBounds=True)
        # def mouseMoved_p2(evt):
        #     pos = evt  # 获取鼠标位置
        #     if p2.sceneBoundingRect().contains(pos):
        #         vLine2.show()
        #         hLine2.show()
        #         mousePoint = p2.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
        #         index = int(mousePoint.x())
        #         if index >= 0 and index < len(self.BO_data_1):
        #             p2.setLabel(axis='bottom', text="x=%0.1f y=%0.1f 脑氧数据=%0.1f" % (
        #             mousePoint.x(), mousePoint.y(), self.BO_data_2[index]))
        #         vLine2.setPos(mousePoint.x())  # 设置垂直线的位置
        #         hLine2.setPos(mousePoint.y())  # 设置水平线的位置
        #     else:
        #         vLine2.hide()
        #         hLine2.hide()
        # p2.scene().sigMouseMoved.connect(mouseMoved_p2)  # 监听鼠标移动事件
        # self.curve2 = p2.plot(pen='r')  # 绘制一个图形
        # self.curve2.setData(self.BO_data_2)

        EEG_data_lable1 = QTableWidgetItem("脑电数据1 = 0.0")
        EEG_data_lable1.setIcon(red_icon)
        EEG_data_lable2 = QTableWidgetItem("脑电数据2 = 0.0")
        EEG_data_lable2.setIcon(green_icon)
        EEG_data_lable3 = QTableWidgetItem("脑电数据3 = 0.0")
        EEG_data_lable3.setIcon(blue_icon)
        EEG_data_lable4 = QTableWidgetItem("脑电数据4 = 0.0")
        EEG_data_lable4.setIcon(yellow_icon)
        EEG_data_lable5 = QTableWidgetItem("脑电数据5 = 0.0")
        EEG_data_lable5.setIcon(magenta_icon)
        EEG_data_label6 = QTableWidgetItem("脑电数据6 = 0.0")
        EEG_data_label6.setIcon(orange_icon)
        EEG_data_lable7 = QTableWidgetItem("脑电数据7 = 0.0")
        EEG_data_lable7.setIcon(purple_icon)
        EEG_data_lable8 = QTableWidgetItem("脑电数据8 = 0.0")
        EEG_data_lable8.setIcon(cyan_icon)

        EEG_t1 = self.ui.EEGtableWidget

        # 均匀拉伸
        # EEG_t1.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # EEG_t1.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)

        EEG_t1.setItem(0, 0, EEG_data_lable1)
        EEG_t1.setItem(0, 1, EEG_data_lable2)
        EEG_t1.setItem(1, 0, EEG_data_lable3)
        EEG_t1.setItem(1, 1, EEG_data_lable4)
        EEG_t1.setItem(2, 0, EEG_data_lable5)
        EEG_t1.setItem(2, 1, EEG_data_label6)
        EEG_t1.setItem(3, 0, EEG_data_lable7)
        EEG_t1.setItem(3, 1, EEG_data_lable8)

        # 绘制脑电数据波形
        EEG_p1 = self.ui.EEG_display1.addPlot(title="脑电数据波形")
        EEG_p1.showGrid(x=True, y=True)  # 把X和Y的表格打开
        EEG_p1.setRange(xRange=[0, 1000], padding=0)
        v1 = pg.InfiniteLine(angle=90, movable=False)
        h1 = pg.InfiniteLine(angle=0, movable=False)
        EEG_p1.addItem(v1, ignoreBounds=True)
        EEG_p1.addItem(h1, ignoreBounds=True)
        def mouseMoved1(evt):
            pos = evt  # 获取鼠标位置
            if EEG_p1.sceneBoundingRect().contains(pos):
                v1.show()
                h1.show()
                mousePoint = EEG_p1.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
                index = int(mousePoint.x())
                if index >= 0 and index < len(EEG_data_1):
                    EEG_p1.setLabel(axis='bottom', text="x=%0.1f y=%0.1f" % (
                        mousePoint.x(), mousePoint.y()))
                    EEG_data_lable1.setText("脑电数据1 = " + f"{EEG_data_1[index]:.1f}")
                    EEG_data_lable2.setText("脑电数据2 = " + f"{EEG_data_2[index]:.1f}")
                    EEG_data_lable3.setText("脑电数据3 = " + f"{EEG_data_3[index]:.1f}")
                    EEG_data_lable4.setText("脑电数据4 = " + f"{EEG_data_4[index]:.1f}")
                    EEG_data_lable5.setText("脑电数据5 = " + f"{EEG_data_5[index]:.1f}")
                    EEG_data_label6.setText("脑电数据6 = " + f"{EEG_data_6[index]:.1f}")
                    EEG_data_lable7.setText("脑电数据7 = " + f"{EEG_data_7[index]:.1f}")
                    EEG_data_lable8.setText("脑电数据8 = " + f"{EEG_data_8[index]:.1f}")
                v1.setPos(mousePoint.x())  # 设置垂直线的位置
                h1.setPos(mousePoint.y())  # 设置水平线的位置
            else:
                v1.hide()
                h1.hide()
        EEG_p1.scene().sigMouseMoved.connect(mouseMoved1)  # 监听鼠标移动事件
        self.EEG_curve1 = EEG_p1.plot(pen='r')  # 绘制一个图形
        self.EEG_curve1.setData(EEG_data_1)
        self.EEG_curve2 = EEG_p1.plot(pen='g')  # 绘制一个图形
        self.EEG_curve2.setData(EEG_data_2)
        self.EEG_curve3 = EEG_p1.plot(pen='b')  # 绘制一个图形
        self.EEG_curve3.setData(EEG_data_3)
        self.EEG_curve4 = EEG_p1.plot(pen='y')  # 绘制一个图形
        self.EEG_curve4.setData(EEG_data_4)
        self.EEG_curve5 = EEG_p1.plot(pen='m')  # 绘制一个图形
        self.EEG_curve5.setData(EEG_data_5)
        self.EEG_curve6 = EEG_p1.plot(pen='orange')  # 绘制一个图形
        self.EEG_curve6.setData(EEG_data_6)
        self.EEG_curve7 = EEG_p1.plot(pen='purple')  # 绘制一个图形
        self.EEG_curve7.setData(EEG_data_7)
        self.EEG_curve8 = EEG_p1.plot(pen='c')  # 绘制一个图形
        self.EEG_curve8.setData(EEG_data_8)

        # EEG_p2 = self.ui.EEG_display2.addPlot(title="脑电数据2波形")
        # EEG_p2.showGrid(x=True, y=True)  # 把X和Y的表格打开
        # EEG_p2.setRange(xRange=[0, 1000], padding=0)
        # v2 = pg.InfiniteLine(angle=90, movable=False)
        # h2 = pg.InfiniteLine(angle=0, movable=False)
        # EEG_p2.addItem(v2, ignoreBounds=True)
        # EEG_p2.addItem(h2, ignoreBounds=True)
        # def mouseMoved2(evt):
        #     pos = evt  # 获取鼠标位置
        #     if EEG_p2.sceneBoundingRect().contains(pos):
        #         v2.show()
        #         h2.show()
        #         mousePoint = EEG_p2.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
        #         index = int(mousePoint.x())
        #         if index >= 0 and index < len(EEG_data_2):
        #             EEG_p2.setLabel(axis='bottom', text="x=%0.1f y=%0.1f 脑电数据=%0.1f" % (
        #                 mousePoint.x(), mousePoint.y(), EEG_data_2[index]))
        #         v2.setPos(mousePoint.x())  # 设置垂直线的位置
        #         h2.setPos(mousePoint.y())  # 设置水平线的位置
        #     else:
        #         v2.hide()
        #         h2.hide()
        # EEG_p2.scene().sigMouseMoved.connect(mouseMoved2)  # 监听鼠标移动事件
        # self.EEG_curve2 = EEG_p2.plot(pen='r')  # 绘制一个图形
        # self.EEG_curve2.setData(EEG_data_2)
        #
        # EEG_p3 = self.ui.EEG_display3.addPlot(title="脑电数据3波形")
        # EEG_p3.showGrid(x=True, y=True)  # 把X和Y的表格打开
        # EEG_p3.setRange(xRange=[0, 1000], padding=0)
        # v3 = pg.InfiniteLine(angle=90, movable=False)
        # h3 = pg.InfiniteLine(angle=0, movable=False)
        # EEG_p3.addItem(v3, ignoreBounds=True)
        # EEG_p3.addItem(h3, ignoreBounds=True)
        # def mouseMoved3(evt):
        #     pos = evt  # 获取鼠标位置
        #     if EEG_p3.sceneBoundingRect().contains(pos):
        #         v3.show()
        #         h3.show()
        #         mousePoint = EEG_p3.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
        #         index = int(mousePoint.x())
        #         if index >= 0 and index < len(EEG_data_3):
        #             EEG_p3.setLabel(axis='bottom', text="x=%0.1f y=%0.1f 脑电数据=%0.1f" % (
        #                 mousePoint.x(), mousePoint.y(), EEG_data_3[index]))
        #         v3.setPos(mousePoint.x())  # 设置垂直线的位置
        #         h3.setPos(mousePoint.y())  # 设置水平线的位置
        #     else:
        #         v3.hide()
        #         h3.hide()
        # EEG_p3.scene().sigMouseMoved.connect(mouseMoved3)  # 监听鼠标移动事件
        # self.EEG_curve3 = EEG_p3.plot(pen='r')  # 绘制一个图形
        # self.EEG_curve3.setData(EEG_data_3)
        #
        # EEG_p4 = self.ui.EEG_display4.addPlot(title="脑电数据4波形")
        # EEG_p4.showGrid(x=True, y=True)  # 把X和Y的表格打开
        # EEG_p4.setRange(xRange=[0, 1000], padding=0)
        # v4 = pg.InfiniteLine(angle=90, movable=False)
        # h4 = pg.InfiniteLine(angle=0, movable=False)
        # EEG_p4.addItem(v4, ignoreBounds=True)
        # EEG_p4.addItem(h4, ignoreBounds=True)
        # def mouseMoved4(evt):
        #     pos = evt  # 获取鼠标位置
        #     if EEG_p4.sceneBoundingRect().contains(pos):
        #         v4.show()
        #         h4.show()
        #         mousePoint = EEG_p4.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
        #         index = int(mousePoint.x())
        #         if index >= 0 and index < len(EEG_data_4):
        #             EEG_p4.setLabel(axis='bottom', text="x=%0.1f y=%0.1f 脑电数据=%0.1f" % (
        #                 mousePoint.x(), mousePoint.y(), EEG_data_4[index]))
        #         v4.setPos(mousePoint.x())  # 设置垂直线的位置
        #         h4.setPos(mousePoint.y())  # 设置水平线的位置
        #     else:
        #         v4.hide()
        #         h4.hide()
        # EEG_p4.scene().sigMouseMoved.connect(mouseMoved4)  # 监听鼠标移动事件
        # self.EEG_curve4 = EEG_p4.plot(pen='r')  # 绘制一个图形
        # self.EEG_curve4.setData(EEG_data_4)
        #
        # EEG_p5 = self.ui.EEG_display5.addPlot(title="脑电数据5波形")
        # EEG_p5.showGrid(x=True, y=True)  # 把X和Y的表格打开
        # EEG_p5.setRange(xRange=[0, 1000], padding=0)
        # # EEG_p5.setLabel(axis='bottom', text='x ')
        # v5 = pg.InfiniteLine(angle=90, movable=False)
        # h5 = pg.InfiniteLine(angle=0, movable=False)
        # EEG_p5.addItem(v5, ignoreBounds=True)
        # EEG_p5.addItem(h5, ignoreBounds=True)
        # def mouseMoved5(evt):
        #     pos = evt  # 获取鼠标位置
        #     if EEG_p5.sceneBoundingRect().contains(pos):
        #         v5.show()
        #         h5.show()
        #         mousePoint = EEG_p5.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
        #         index = int(mousePoint.x())
        #         if index >= 0 and index < len(EEG_data_5):
        #             EEG_p5.setLabel(axis='bottom', text="x=%0.1f y=%0.1f 脑电数据=%0.1f" % (
        #                 mousePoint.x(), mousePoint.y(), EEG_data_5[index]))
        #         v5.setPos(mousePoint.x())  # 设置垂直线的位置
        #         h5.setPos(mousePoint.y())  # 设置水平线的位置
        #     else:
        #         v5.hide()
        #         h5.hide()
        # EEG_p5.scene().sigMouseMoved.connect(mouseMoved5)  # 监听鼠标移动事件
        # self.EEG_curve5 = EEG_p5.plot(pen='r')  # 绘制一个图形
        # self.EEG_curve5.setData(EEG_data_5)
        #
        # EEG_p6 = self.ui.EEG_display6.addPlot(title="脑电数据6波形")
        # EEG_p6.showGrid(x=True, y=True)  # 把X和Y的表格打开
        # EEG_p6.setRange(xRange=[0, 1000], padding=0)
        # # EEG_p6.setLabel(axis='bottom', text='x ')
        # v6 = pg.InfiniteLine(angle=90, movable=False)
        # h6 = pg.InfiniteLine(angle=0, movable=False)
        # EEG_p6.addItem(v6, ignoreBounds=True)
        # EEG_p6.addItem(h6, ignoreBounds=True)
        # def mouseMoved6(evt):
        #     pos = evt  # 获取鼠标位置
        #     if EEG_p6.sceneBoundingRect().contains(pos):
        #         v6.show()
        #         h6.show()
        #         mousePoint = EEG_p6.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
        #         index = int(mousePoint.x())
        #         if index >= 0 and index < len(EEG_data_6):
        #             EEG_p6.setLabel(axis='bottom', text="x=%0.1f y=%0.1f 脑电数据=%0.1f" % (
        #                 mousePoint.x(), mousePoint.y(), EEG_data_6[index]))
        #         v6.setPos(mousePoint.x())  # 设置垂直线的位置
        #         h6.setPos(mousePoint.y())  # 设置水平线的位置
        #     else:
        #         v6.hide()
        #         h6.hide()
        # EEG_p6.scene().sigMouseMoved.connect(mouseMoved6)  # 监听鼠标移动事件
        # self.EEG_curve6 = EEG_p6.plot(pen='r')  # 绘制一个图形
        # self.EEG_curve6.setData(EEG_data_6)
        #
        # EEG_p7 = self.ui.EEG_display7.addPlot(title="脑电数据7波形")
        # EEG_p7.showGrid(x=True, y=True)  # 把X和Y的表格打开
        # EEG_p7.setRange(xRange=[0, 1000], padding=0)
        # # EEG_p7.setLabel(axis='bottom', text='x ')
        # v7 = pg.InfiniteLine(angle=90, movable=False)
        # h7 = pg.InfiniteLine(angle=0, movable=False)
        # EEG_p7.addItem(v7, ignoreBounds=True)
        # EEG_p7.addItem(h7, ignoreBounds=True)
        # def mouseMoved7(evt):
        #     pos = evt  # 获取鼠标位置
        #     if EEG_p7.sceneBoundingRect().contains(pos):
        #         v7.show()
        #         h7.show()
        #         mousePoint = EEG_p7.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
        #         index = int(mousePoint.x())
        #         if index >= 0 and index < len(EEG_data_7):
        #             EEG_p7.setLabel(axis='bottom', text="x=%0.1f y=%0.1f 脑电数据=%0.1f" % (
        #                 mousePoint.x(), mousePoint.y(), EEG_data_7[index]))
        #         v7.setPos(mousePoint.x())  # 设置垂直线的位置
        #         h7.setPos(mousePoint.y())  # 设置水平线的位置
        #     else:
        #         v7.hide()
        #         h7.hide()
        # EEG_p7.scene().sigMouseMoved.connect(mouseMoved7)  # 监听鼠标移动事件
        # self.EEG_curve7 = EEG_p7.plot(pen='r')  # 绘制一个图形
        # self.EEG_curve7.setData(EEG_data_7)
        #
        # EEG_p8 = self.ui.EEG_display8.addPlot(title="脑电数据8波形")
        # EEG_p8.showGrid(x=True, y=True)  # 把X和Y的表格打开
        # EEG_p8.setRange(xRange=[0, 1000], padding=0)
        # # EEG_p8.setLabel(axis='bottom', text='x ')
        # v8 = pg.InfiniteLine(angle=90, movable=False)
        # h8 = pg.InfiniteLine(angle=0, movable=False)
        # EEG_p8.addItem(v8, ignoreBounds=True)
        # EEG_p8.addItem(h8, ignoreBounds=True)
        # def mouseMoved8(evt):
        #     pos = evt  # 获取鼠标位置
        #     if EEG_p8.sceneBoundingRect().contains(pos):
        #         v8.show()
        #         h8.show()
        #         mousePoint = EEG_p8.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
        #         index = int(mousePoint.x())
        #         if index >= 0 and index < len(EEG_data_8):
        #             EEG_p8.setLabel(axis='bottom', text="x=%0.1f y=%0.1f 脑电数据=%0.1f" % (
        #                 mousePoint.x(), mousePoint.y(), EEG_data_8[index]))
        #         v8.setPos(mousePoint.x())  # 设置垂直线的位置
        #         h8.setPos(mousePoint.y())  # 设置水平线的位置
        #     else:
        #         v8.hide()
        #         h8.hide()
        # EEG_p8.scene().sigMouseMoved.connect(mouseMoved8)  # 监听鼠标移动事件
        # self.EEG_curve8 = EEG_p8.plot(pen='r')  # 绘制一个图形
        # self.EEG_curve8.setData(EEG_data_8)

        # 颜色图标
        impedance_data_lable1 = QTableWidgetItem("阻抗数据1 = 0.0")
        impedance_data_lable1.setIcon(red_icon)
        impedance_data_lable2 = QTableWidgetItem("阻抗数据2 = 0.0")
        impedance_data_lable2.setIcon(green_icon)
        impedance_data_lable3 = QTableWidgetItem("阻抗数据3 = 0.0")
        impedance_data_lable3.setIcon(blue_icon)
        impedance_data_lable4 = QTableWidgetItem("阻抗数据4 = 0.0")
        impedance_data_lable4.setIcon(yellow_icon)
        impedance_data_lable5 = QTableWidgetItem("阻抗数据5 = 0.0")
        impedance_data_lable5.setIcon(magenta_icon)
        impedance_data_label6 = QTableWidgetItem("阻抗数据6 = 0.0")
        impedance_data_label6.setIcon(orange_icon)
        impedance_data_lable7 = QTableWidgetItem("阻抗数据7 = 0.0")
        impedance_data_lable7.setIcon(purple_icon)
        impedance_data_lable8 = QTableWidgetItem("阻抗数据8 = 0.0")
        impedance_data_lable8.setIcon(cyan_icon)

        # 绘制阻抗数据图例
        impedance_t1 = self.ui.impedancetableWidget

        # 均匀拉伸
        # impedance_t1.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # impedance_t1.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)

        impedance_t1.setItem(0, 0, impedance_data_lable1)
        impedance_t1.setItem(0, 1, impedance_data_lable2)
        impedance_t1.setItem(1, 0, impedance_data_lable3)
        impedance_t1.setItem(1, 1, impedance_data_lable4)
        impedance_t1.setItem(2, 0, impedance_data_lable5)
        impedance_t1.setItem(2, 1, impedance_data_label6)
        impedance_t1.setItem(3, 0, impedance_data_lable7)
        impedance_t1.setItem(3, 1, impedance_data_lable8)

        impedance_p1 = self.ui.impedance_display1.addPlot(title="阻抗数据波形")
        impedance_p1.showGrid(x=True, y=True)  # 把X和Y的表格打开
        impedance_p1.setRange(xRange=[0, 1000], padding=0)
        # impedance_p1.setLabel(axis='bottom', text='x ')
        impedance_v1 = pg.InfiniteLine(angle=90, movable=False)
        impedance_h1 = pg.InfiniteLine(angle=0, movable=False)
        impedance_p1.addItem(impedance_v1, ignoreBounds=True)
        impedance_p1.addItem(impedance_h1, ignoreBounds=True)
        def mouseMoved_impedance_1(evt):
            pos = evt  # 获取鼠标位置
            if impedance_p1.sceneBoundingRect().contains(pos):
                impedance_v1.show()
                impedance_h1.show()
                mousePoint = impedance_p1.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
                index = int(mousePoint.x())
                if index >= 0 and index < len(impedance_data_1):
                    impedance_p1.setLabel(axis='bottom', text="x=%0.1f y=%0.1f" % (
                        mousePoint.x(), mousePoint.y()))
                    impedance_data_lable1.setText("阻抗数据1 = " + f"{impedance_data_1[index]:.1f}" )
                    impedance_data_lable2.setText("阻抗数据2 = " + f"{impedance_data_2[index]:.1f}" )
                    impedance_data_lable3.setText("阻抗数据3 = " + f"{impedance_data_3[index]:.1f}" )
                    impedance_data_lable4.setText("阻抗数据4 = " + f"{impedance_data_4[index]:.1f}" )
                    impedance_data_lable5.setText("阻抗数据5 = " + f"{impedance_data_5[index]:.1f}" )
                    impedance_data_label6.setText("阻抗数据6 = " + f"{impedance_data_6[index]:.1f}" )
                    impedance_data_lable7.setText("阻抗数据7 = " + f"{impedance_data_7[index]:.1f}" )
                    impedance_data_lable8.setText("阻抗数据8 = " + f"{impedance_data_8[index]:.1f}" )

                impedance_v1.setPos(mousePoint.x())  # 设置垂直线的位置
                impedance_h1.setPos(mousePoint.y())  # 设置水平线的位置
            else:
                impedance_v1.hide()
                impedance_h1.hide()
        impedance_p1.scene().sigMouseMoved.connect(mouseMoved_impedance_1)  # 监听鼠标移动事件
        self.impedance_curve1 = impedance_p1.plot(pen='r')  # 绘制一个图形
        self.impedance_curve1.setData(impedance_data_1)
        self.impedance_curve2 = impedance_p1.plot(pen='g')  # 绘制一个图形
        self.impedance_curve2.setData(impedance_data_2)
        self.impedance_curve3 = impedance_p1.plot(pen='b')  # 绘制一个图形
        self.impedance_curve3.setData(impedance_data_3)
        self.impedance_curve4 = impedance_p1.plot(pen='y')  # 绘制一个图形
        self.impedance_curve4.setData(impedance_data_4)
        self.impedance_curve5 = impedance_p1.plot(pen='m')  # 绘制一个图形
        self.impedance_curve5.setData(impedance_data_5)
        self.impedance_curve6 = impedance_p1.plot(pen='orange')  # 绘制一个图形
        self.impedance_curve6.setData(impedance_data_6)
        self.impedance_curve7 = impedance_p1.plot(pen='purple')  # 绘制一个图形
        self.impedance_curve7.setData(impedance_data_7)
        self.impedance_curve8 = impedance_p1.plot(pen='c')  # 绘制一个图形
        self.impedance_curve8.setData(impedance_data_8)

        # impedance_p2 = self.ui.impedance_display2.addPlot(title="阻抗数据2波形")
        # impedance_p2.showGrid(x=True, y=True)  # 把X和Y的表格打开
        # impedance_p2.setRange(xRange=[0, 1000], padding=0)
        # # impedance_p2.setLabel(axis='bottom', text='x ')
        # impedance_v2 = pg.InfiniteLine(angle=90, movable=False)
        # impedance_h2 = pg.InfiniteLine(angle=0, movable=False)
        # impedance_p2.addItem(impedance_v2, ignoreBounds=True)
        # impedance_p2.addItem(impedance_h2, ignoreBounds=True)
        # def mouseMoved_impedance_2(evt):
        #     pos = evt  # 获取鼠标位置
        #     if impedance_p2.sceneBoundingRect().contains(pos):
        #         impedance_v2.show()
        #         impedance_h2.show()
        #         mousePoint = impedance_p2.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
        #         index = int(mousePoint.x())
        #         if index >= 0 and index < len(impedance_data_2):
        #             impedance_p2.setLabel(axis='bottom', text="x=%0.1f y=%0.1f 阻抗数据=%0.1f" % (
        #                 mousePoint.x(), mousePoint.y(), impedance_data_2[index]))
        #         impedance_v2.setPos(mousePoint.x())  # 设置垂直线的位置
        #         impedance_h2.setPos(mousePoint.y())  # 设置水平线的位置
        #     else:
        #         impedance_v2.hide()
        #         impedance_h2.hide()
        # impedance_p2.scene().sigMouseMoved.connect(mouseMoved_impedance_2)  # 监听鼠标移动事件
        # self.impedance_curve2 = impedance_p2.plot(pen='r')  # 绘制一个图形
        # self.impedance_curve2.setData(impedance_data_2)
        #
        # impedance_p3 = self.ui.impedance_display3.addPlot(title="阻抗数据3波形")
        # impedance_p3.showGrid(x=True, y=True)  # 把X和Y的表格打开
        # impedance_p3.setRange(xRange=[0, 1000], padding=0)
        # # impedance_p3.setLabel(axis='bottom', text='x ')
        # impedance_v3 = pg.InfiniteLine(angle=90, movable=False)
        # impedance_h3 = pg.InfiniteLine(angle=0, movable=False)
        # impedance_p3.addItem(impedance_v3, ignoreBounds=True)
        # impedance_p3.addItem(impedance_h3, ignoreBounds=True)
        # def mouseMoved_impedance_3(evt):
        #     pos = evt  # 获取鼠标位置
        #     if impedance_p3.sceneBoundingRect().contains(pos):
        #         impedance_v3.show()
        #         impedance_h3.show()
        #         mousePoint = impedance_p3.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
        #         index = int(mousePoint.x())
        #         if index >= 0 and index < len(impedance_data_3):
        #             impedance_p3.setLabel(axis='bottom', text="x=%0.1f y=%0.1f 阻抗数据=%0.1f" % (
        #                 mousePoint.x(), mousePoint.y(), impedance_data_3[index]))
        #         impedance_v3.setPos(mousePoint.x())  # 设置垂直线的位置
        #         impedance_h3.setPos(mousePoint.y())  # 设置水平线的位置
        #     else:
        #         impedance_v3.hide()
        #         impedance_h3.hide()
        # impedance_p3.scene().sigMouseMoved.connect(mouseMoved_impedance_3)  # 监听鼠标移动事件
        # self.impedance_curve3 = impedance_p3.plot(pen='r')  # 绘制一个图形
        # self.impedance_curve3.setData(impedance_data_3)
        #
        # impedance_p4 = self.ui.impedance_display4.addPlot(title="阻抗数据4波形")
        # impedance_p4.showGrid(x=True, y=True)  # 把X和Y的表格打开
        # impedance_p4.setRange(xRange=[0, 1000], padding=0)
        # # impedance_p4.setLabel(axis='bottom', text='x ')
        # impedance_v4 = pg.InfiniteLine(angle=90, movable=False)
        # impedance_h4 = pg.InfiniteLine(angle=0, movable=False)
        # impedance_p4.addItem(impedance_v4, ignoreBounds=True)
        # impedance_p4.addItem(impedance_h4, ignoreBounds=True)
        # def mouseMoved_impedance_4(evt):
        #     pos = evt  # 获取鼠标位置
        #     if impedance_p4.sceneBoundingRect().contains(pos):
        #         impedance_v4.show()
        #         impedance_h4.show()
        #         mousePoint = impedance_p4.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
        #         index = int(mousePoint.x())
        #         if index >= 0 and index < len(impedance_data_4):
        #             impedance_p4.setLabel(axis='bottom', text="x=%0.1f y=%0.1f 阻抗数据=%0.1f" % (
        #                 mousePoint.x(), mousePoint.y(), impedance_data_4[index]))
        #         impedance_v4.setPos(mousePoint.x())  # 设置垂直线的位置
        #         impedance_h4.setPos(mousePoint.y())  # 设置水平线的位置
        #     else:
        #         impedance_v4.hide()
        #         impedance_h4.hide()
        # impedance_p4.scene().sigMouseMoved.connect(mouseMoved_impedance_4)  # 监听鼠标移动事件
        # self.impedance_curve4 = impedance_p4.plot(pen='r')  # 绘制一个图形
        # self.impedance_curve4.setData(impedance_data_4)
        #
        # impedance_p5 = self.ui.impedance_display5.addPlot(title="阻抗数据5波形")
        # impedance_p5.showGrid(x=True, y=True)  # 把X和Y的表格打开
        # impedance_p5.setRange(xRange=[0, 1000], padding=0)
        # # impedance_p5.setLabel(axis='bottom', text='x ')
        # impedance_v5 = pg.InfiniteLine(angle=90, movable=False)
        # impedance_h5 = pg.InfiniteLine(angle=0, movable=False)
        # impedance_p5.addItem(impedance_v5, ignoreBounds=True)
        # impedance_p5.addItem(impedance_h5, ignoreBounds=True)
        # def mouseMoved_impedance_5(evt):
        #     pos = evt  # 获取鼠标位置
        #     if impedance_p5.sceneBoundingRect().contains(pos):
        #         impedance_v5.show()
        #         impedance_h5.show()
        #         mousePoint = impedance_p5.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
        #         index = int(mousePoint.x())
        #         if index >= 0 and index < len(impedance_data_5):
        #             impedance_p5.setLabel(axis='bottom', text="x=%0.1f y=%0.1f 阻抗数据=%0.1f" % (
        #                 mousePoint.x(), mousePoint.y(), impedance_data_5[index]))
        #         impedance_v5.setPos(mousePoint.x())  # 设置垂直线的位置
        #         impedance_h5.setPos(mousePoint.y())  # 设置水平线的位置
        #     else:
        #         impedance_v5.hide()
        #         impedance_h5.hide()
        # impedance_p5.scene().sigMouseMoved.connect(mouseMoved_impedance_5)  # 监听鼠标移动事件
        # self.impedance_curve5 = impedance_p5.plot(pen='r')  # 绘制一个图形
        # self.impedance_curve5.setData(impedance_data_5)
        #
        # impedance_p6 = self.ui.impedance_display6.addPlot(title="阻抗数据6波形")
        # impedance_p6.showGrid(x=True, y=True)  # 把X和Y的表格打开
        # impedance_p6.setRange(xRange=[0, 1000], padding=0)
        # # impedance_p6.setLabel(axis='bottom', text='x ')
        # impedance_v6 = pg.InfiniteLine(angle=90, movable=False)
        # impedance_h6 = pg.InfiniteLine(angle=0, movable=False)
        # impedance_p6.addItem(impedance_v6, ignoreBounds=True)
        # impedance_p6.addItem(impedance_h6, ignoreBounds=True)
        # def mouseMoved_impedance_6(evt):
        #     pos = evt  # 获取鼠标位置
        #     if impedance_p6.sceneBoundingRect().contains(pos):
        #         impedance_v6.show()
        #         impedance_h6.show()
        #         mousePoint = impedance_p6.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
        #         index = int(mousePoint.x())
        #         if index >= 0 and index < len(impedance_data_6):
        #             impedance_p6.setLabel(axis='bottom', text="x=%0.1f y=%0.1f 阻抗数据=%0.1f" % (
        #                 mousePoint.x(), mousePoint.y(), impedance_data_6[index]))
        #         impedance_v6.setPos(mousePoint.x())  # 设置垂直线的位置
        #         impedance_h6.setPos(mousePoint.y())  # 设置水平线的位置
        #     else:
        #         impedance_v6.hide()
        #         impedance_h6.hide()
        # impedance_p6.scene().sigMouseMoved.connect(mouseMoved_impedance_6)  # 监听鼠标移动事件
        # self.impedance_curve6 = impedance_p6.plot(pen='r')  # 绘制一个图形
        # self.impedance_curve6.setData(impedance_data_6)
        #
        # impedance_p7 = self.ui.impedance_display7.addPlot(title="阻抗数据7波形")
        # impedance_p7.showGrid(x=True, y=True)  # 把X和Y的表格打开
        # impedance_p7.setRange(xRange=[0, 1000], padding=0)
        # # impedance_p7.setLabel(axis='bottom', text='x ')
        # impedance_v7 = pg.InfiniteLine(angle=90, movable=False)
        # impedance_h7 = pg.InfiniteLine(angle=0, movable=False)
        # impedance_p7.addItem(impedance_v7, ignoreBounds=True)
        # impedance_p7.addItem(impedance_h7, ignoreBounds=True)
        # def mouseMoved_impedance_7(evt):
        #     pos = evt  # 获取鼠标位置
        #     if impedance_p7.sceneBoundingRect().contains(pos):
        #         impedance_v7.show()
        #         impedance_h7.show()
        #         mousePoint = impedance_p7.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
        #         index = int(mousePoint.x())
        #         if index >= 0 and index < len(impedance_data_7):
        #             impedance_p7.setLabel(axis='bottom', text="x=%0.1f y=%0.1f 阻抗数据=%0.1f" % (
        #                 mousePoint.x(), mousePoint.y(), impedance_data_7[index]))
        #         impedance_v7.setPos(mousePoint.x())  # 设置垂直线的位置
        #         impedance_h7.setPos(mousePoint.y())  # 设置水平线的位置
        #     else:
        #         impedance_v7.hide()
        #         impedance_h7.hide()
        # impedance_p7.scene().sigMouseMoved.connect(mouseMoved_impedance_7)  # 监听鼠标移动事件
        # self.impedance_curve7 = impedance_p7.plot(pen='r')  # 绘制一个图形
        # self.impedance_curve7.setData(impedance_data_7)
        #
        # impedance_p8 = self.ui.impedance_display8.addPlot(title="阻抗数据8波形")
        # impedance_p8.showGrid(x=True, y=True)  # 把X和Y的表格打开
        # impedance_p8.setRange(xRange=[0, 1000], padding=0)
        # # impedance_p6.setLabel(axis='bottom', text='x ')
        # impedance_v8 = pg.InfiniteLine(angle=90, movable=False)
        # impedance_h8 = pg.InfiniteLine(angle=0, movable=False)
        # impedance_p8.addItem(impedance_v8, ignoreBounds=True)
        # impedance_p8.addItem(impedance_h8, ignoreBounds=True)
        # def mouseMoved_impedance_8(evt):
        #     pos = evt  # 获取鼠标位置
        #     if impedance_p8.sceneBoundingRect().contains(pos):
        #         impedance_v8.show()
        #         impedance_h8.show()
        #         mousePoint = impedance_p8.vb.mapSceneToView(pos)  # 将鼠标位置转换为绘图坐标系中的坐标
        #         index = int(mousePoint.x())
        #         if index >= 0 and index < len(impedance_data_8):
        #             impedance_p8.setLabel(axis='bottom', text="x=%0.1f y=%0.1f 阻抗数据=%0.1f" % (
        #                 mousePoint.x(), mousePoint.y(), impedance_data_8[index]))
        #         impedance_v8.setPos(mousePoint.x())  # 设置垂直线的位置
        #         impedance_h8.setPos(mousePoint.y())  # 设置水平线的位置
        #     else:
        #         impedance_v8.hide()
        #         impedance_h8.hide()
        # impedance_p8.scene().sigMouseMoved.connect(mouseMoved_impedance_8)  # 监听鼠标移动事件
        # self.impedance_curve8 = impedance_p8.plot(pen='r')  # 绘制一个图形
        # self.impedance_curve8.setData(impedance_data_8)



        # tDCS模块
        self.ui.pushButton.clicked.connect(self.run_tDCS)
        self.ui.pushButton_2.clicked.connect(self.stop_tDCS)
        self.ui.radioButton_4.clicked.connect(self.alternating_current_mode)
        self.ui.radioButton_3.clicked.connect(self.pulse_mode)
        self.ui.radioButton.clicked.connect(self.direct_current_mode)
        self.ui.radioButton_2.clicked.connect(self.random_mode)
        self.ui.radioButton_5.clicked.connect(self.pseudo_stimulus_mode)
        # 电流时间调整
        self.ui.pushButton_7.clicked.connect(self.increase_current)
        self.ui.pushButton_14.clicked.connect(self.decrease_current)
        self.ui.pushButton_13.clicked.connect(self.increase_time)
        self.ui.pushButton_6.clicked.connect(self.decrease_time)
        # 设置电流与时间
        self.ui.pushButton_3.clicked.connect(self.set_current)
        self.ui.pushButton_3.clicked.connect(self.set_tDCS_time)


        # 进度条相关
        self.ui.pushButton_3.clicked.connect(self.updateProgressBarMax)
        self.timer3 = QTimer()  # 创建定时器
        self.timer3.timeout.connect(self.updateProgressBar)  # 连接定时器信号到槽函数
        self.elapsedTime = 0  # 已过时间
        self.maxTime = 0


        # 光刺激模块
        # 模块启动关闭与重置
        self.ui.pushButton_4.clicked.connect(self.run_stimulation)
        self.ui.pushButton_5.clicked.connect(self.stop_stimulation)
        self.ui.pushButton_8.clicked.connect(self.reset_stimulation)
        # 刺激时间
        # self.ui.radioButton_6.clicked.connect(self.set_stimulation_time)
        # self.ui.radioButton_7.clicked.connect(self.set_stimulation_time)
        # self.ui.radioButton_8.clicked.connect(self.set_stimulation_time)
        # self.ui.radioButton_9.clicked.connect(self.set_stimulation_time)

        self.ui.radioButton_6.clicked.connect(self.set_stimulation_time)
        self.ui.radioButton_7.clicked.connect(self.set_stimulation_time)
        self.ui.radioButton_8.clicked.connect(self.set_stimulation_time)
        self.ui.radioButton_9.clicked.connect(self.set_stimulation_time)

        # 刺激频率1
        self.ui.radioButton_10.clicked.connect(self.set_stimulation_frequency1)
        self.ui.radioButton_11.clicked.connect(self.set_stimulation_frequency1)
        self.ui.radioButton_12.clicked.connect(self.set_stimulation_frequency1)
        self.ui.radioButton_13.clicked.connect(self.set_stimulation_frequency1)
        self.ui.radioButton_38.clicked.connect(self.set_stimulation_frequency1)
        # 刺激频率2
        self.ui.radioButton_14.clicked.connect(self.set_stimulation_frequency2)
        self.ui.radioButton_20.clicked.connect(self.set_stimulation_frequency2)
        self.ui.radioButton_25.clicked.connect(self.set_stimulation_frequency2)
        self.ui.radioButton_31.clicked.connect(self.set_stimulation_frequency2)
        self.ui.radioButton_39.clicked.connect(self.set_stimulation_frequency2)
        # 辐照度1
        self.ui.radioButton_15.clicked.connect(self.set_stimulation_irradiance1)
        self.ui.radioButton_16.clicked.connect(self.set_stimulation_irradiance1)
        self.ui.radioButton_17.clicked.connect(self.set_stimulation_irradiance1)
        self.ui.radioButton_18.clicked.connect(self.set_stimulation_irradiance1)
        self.ui.radioButton_19.clicked.connect(self.set_stimulation_irradiance1)
        self.ui.radioButton_40.clicked.connect(self.set_stimulation_irradiance1)
        # 辐照度2
        self.ui.radioButton_33.clicked.connect(self.set_stimulation_irradiance2)
        self.ui.radioButton_34.clicked.connect(self.set_stimulation_irradiance2)
        self.ui.radioButton_35.clicked.connect(self.set_stimulation_irradiance2)
        self.ui.radioButton_36.clicked.connect(self.set_stimulation_irradiance2)
        self.ui.radioButton_37.clicked.connect(self.set_stimulation_irradiance2)
        self.ui.radioButton_41.clicked.connect(self.set_stimulation_irradiance2)







        self.ui.pushButton_47.clicked.connect(self.show_second_page)
        self.ui.pushButton_18.clicked.connect(self.show_first_page)
        self.ui.pushButton_return.clicked.connect(self.show_1_page)
        self.ui.pushButton_22.clicked.connect(self.open_build_electrode)
        self.ui.pushButton_20.clicked.connect(self.open_build_light)
        self.ui.stackedWidget_5.setCurrentIndex(1)
        self.ui.creategroup.clicked.connect(self.createGroup1)
        self.ui.creategroup_2.clicked.connect(self.createGroup2)
        self.ui.creategroup_3.clicked.connect(self.createGroup3)
        # 设置拖放规则

        self.ui.treeWidget.setDragEnabled(True)
        self.ui.treeWidget.setAcceptDrops(True)
        self.ui.treeWidget.setDropIndicatorShown(True)
        self.ui.treeWidget.setDragDropMode(QTreeWidget.InternalMove)
        self.ui.treeWidget_3.setDragEnabled(True)
        self.ui.treeWidget_3.setAcceptDrops(True)
        self.ui.treeWidget_3.setDropIndicatorShown(True)
        self.ui.treeWidget_3.setDragDropMode(QTreeWidget.InternalMove)
        self.ui.treeWidget_2.setDragEnabled(True)
        self.ui.treeWidget_2.setAcceptDrops(True)
        self.ui.treeWidget_2.setDropIndicatorShown(True)
        self.ui.treeWidget_2.setDragDropMode(QTreeWidget.InternalMove)
        # # 重载事件处理函数
        # self.ui.treeWidget.dragEnterEvent = self.dragEnterEvent
        self.ui.treeWidget.dropEvent = self.dropEvent
        # self.ui.treeWidget_3.dragEnterEvent = self.dragEnterEvent
        self.ui.treeWidget_3.dropEvent = self.dropEvent_3
        # self.ui.treeWidget_2.dragEnterEvent = self.dragEnterEvent
        self.ui.treeWidget_2.dropEvent = self.dropEvent_2
        #删除分组
        self.ui.delete_e.clicked.connect(lambda: self.on_delete_clicked(self.ui.treeWidget, '电极仿真'))
        self.ui.delete_l.clicked.connect(lambda: self.on_delete_clicked(self.ui.treeWidget_3, '光源仿真'))
        self.ui.delete_y.clicked.connect(lambda: self.on_delete_clicked(self.ui.treeWidget_2, '优化配置'))
        #点击查看头部模型
        self.ui.pushButton_16.clicked.connect(self.call_show_mesh)
        self.ui.pushButton_45.clicked.connect(self.call_show_T1)
        self.ui.pushButton_46.clicked.connect(self.call_show_T2)
        self.ui.pushButton_44.clicked.connect(self.call_show_cond)
        #创建时选择文件路径
        self.build_electrode.lineEdit_6.mousePressEvent = self.on_click_line_edit_e
        self.build_electrode.lineEdit_2.mousePressEvent = self.on_click_line_edit_e2
        self.build_light.lineEdit_6.mousePressEvent = self.on_click_line_edit_l
        #打开文件
        self.ui.pushButton_49.clicked.connect(self.open_e)
        self.ui.pushButton_50.clicked.connect(self.open_l)
        self.ui.pushButton_51.clicked.connect(self.open_y)



        #软件首页
        #选择文件
        self.ui.pushButton_27.clicked.connect(self.pickAshow1)
        self.ui.pushButton_19.clicked.connect(self.pickAshow2)
        self.ui.pushButton_26.clicked.connect(self.pickAshow3)
        self.ui.pushButton_25.clicked.connect(self.pickAshow4)
        self.ui.pushButton_28.clicked.connect(self.pickAshow5)
        self.ui.pushButton_39.clicked.connect(self.pickAshow8)

        #点击创建按钮，创建头部模型
        self.ui.pushButton_29.clicked.connect(self.createHead)
        #头部模型-取消创建
        self.ui.pushButton_30.clicked.connect(self.cleanInput)
        #选择头部模型文件夹后，点击打开
        self.ui.pushButton_24.clicked.connect(self.nextPage)

        #优化配置页面
        #选择优化配置文件的保存路径
        self.ui.pushButton_11.clicked.connect(self.pickAshow6)
        #添加靶区
        self.ui.pushButton_34.clicked.connect(self.add_area)
        #添加靶网络
        self.ui.pushButton_56.clicked.connect(self.add_net)
        # 添加靶点
        self.ui.pushButton_54.clicked.connect(self.set_dot_flag)
        # 删除靶点
        self.ui.pushButton_55.clicked.connect(self.delet_dot)
        # 添加避免点
        self.ui.pushButton_9.clicked.connect(self.set_avoid_flag)
        # 删除避免点
        self.ui.pushButton_53.clicked.connect(self.delet_avoid)
        #跳转优化配置页面之前，完成页面的初始化
        self.ui.pushButton_15.clicked.connect(self.init_optional)
        #检测优化类型的改变
        self.ui.radioButton_21.toggled.connect(self.MonitorDot)
        self.ui.radioButton_22.toggled.connect(self.MonitorArea)
        self.ui.radioButton_23.toggled.connect(self.MonitorNetwork)
        #优化配置传参
        self.ui.pushButton_12.clicked.connect(self.optional_show)
        #取消按钮跳转页面
        self.ui.pushButton_31.clicked.connect(self.back_head)
        #搜索文件
        self.ui.pushButton_52.clicked.connect(lambda: self.onSearchClicked(self.ui.lineEdit_6, self.ui.treeWidget))
        self.ui.pushButton_48.clicked.connect(lambda: self.onSearchClicked(self.ui.lineEdit_3, self.ui.treeWidget_2))
        self.ui.pushButton_43.clicked.connect(lambda: self.onSearchClicked(self.ui.lineEdit_5, self.ui.treeWidget_3))





    def close_electrode_and_return(self):
        # 关闭当前窗口
        # filename = 'data_log.xlsx'
        # full_path = os.path.join(headModule_path, filename)
        # self.updateTreeWidget(full_path, workbook['电极仿真'], self.ui.treeWidget)
        self.build_electrode.close()
        self.show()

    def close_light_and_return(self):
        # 关闭当前窗口
        # filename = 'data_log.xlsx'
        # full_path = os.path.join(headModule_path, filename)
        # self.updateTreeWidget(full_path, workbook['光源仿真'], self.ui.treeWidget_3)
        self.build_light.close()
        self.show()
    def open_build_light(self):

        # 显示 build_light 对话框
        self.build_light.show()
        groups = []
        for i in range(self.ui.treeWidget_3.topLevelItemCount()):
            parentItem = self.ui.treeWidget_3.topLevelItem(i)
            group = parentItem.text(0)  # 获取父级分组的文本作为分组信息
            groups.append(group)
        unique_groups = list(set(groups))
        if not unique_groups:  # 检查列表是否为空
            QMessageBox.information(self, '错误', '请先创建分组！')
            self.build_light.close()
            self.show()
        else:
            self.build_light.comboBox.clear()  # 清空现有的选项
            self.build_light.comboBox.addItems(unique_groups)  # 添加新的选项
            self.hide()

    def open_build_electrode(self):
        self.build_electrode.show()
        groups = []
        for i in range(self.ui.treeWidget.topLevelItemCount()):
            parentItem = self.ui.treeWidget.topLevelItem(i)
            group = parentItem.text(0)  # 获取父级分组的文本作为分组信息
            groups.append(group)
        unique_groups = list(set(groups))
        if not unique_groups:  # 检查列表是否为空
            QMessageBox.information(self, '错误', '请先创建分组！')
            self.build_light.close()
            self.show()
        else:
            self.build_electrode.comboBox.clear()  # 清空现有的选项
            self.build_electrode.comboBox.addItems(unique_groups)  # 添加新的选项
            self.hide()

    def return_mainwindow(self):
        self.hide()
        self.return_mainwindow.show()

    def on_click_line_edit_e(self, event):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        directory = QFileDialog.getExistingDirectory(self, "选择文件夹", "", options=options)
        if directory:
            self.build_electrode.lineEdit_6.setText(directory)
    def on_click_line_edit_e2(self, event):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        # 使用 getOpenFileName 来选择文件，而不是 getExistingDirectory
        fileName, _ = QFileDialog.getOpenFileName(self, "选择CSV文件", "", "CSV Files (*.csv)", options=options)
        if fileName:
            # 将选择的文件路径设置到 lineEdit_2 中
            self.build_electrode.lineEdit_2.setText(fileName)
            # 读取CSV文件，并在QTableWidget中显示数据
            #self.build_electrode.tableWidget.display_data_in_table(fileName)
            # 读取CSV文件，header=None表示文件中没有表头
            df = pd.read_csv(fileName, header=None)

            # 筛选出第二列非零的行
            df_short = df[df[1] != 0]

            # 获取第一列和第二列的值
            names = df_short[0].tolist()  # 电极名称
            currents = df_short[1].tolist()  # 电流值

            # 设置QTableWidget的行数和列数
            self.build_electrode.tableWidget.setRowCount(len(names))
            self.build_electrode.tableWidget.setColumnCount(2)
            self.build_electrode.tableWidget.setHorizontalHeaderLabels(['电极名称', '电流'])

            # 将数据填充到QTableWidget中
            for row_idx, (name, current) in enumerate(zip(names, currents)):
                self.build_electrode.tableWidget.setItem(row_idx, 0, QTableWidgetItem(str(name)))
                self.build_electrode.tableWidget.setItem(row_idx, 1, QTableWidgetItem(str(current)))




    def on_click_line_edit_l(self, event):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        directory = QFileDialog.getExistingDirectory(self, "选择文件夹", "", options=options)
        if directory:
            self.build_light.lineEdit_6.setText(directory)





    def onSearchClicked(self, lineEdit, treeWidget):
        searchText = lineEdit.text().lower()  # 获取输入框的文本并转换为小写
        treeWidget.clearSelection()  # 清除之前的选中项
        found = self.searchItems(treeWidget, searchText)  # 从树形控件开始搜索
        if found:
            treeWidget.setCurrentItem(found)  # 如果找到，设置当前项
        else:
            self.showError("未找到匹配项。请尝试其他关键词。")  # 搜索未找到时显示错误消息

    def searchItems(self, treeWidget, searchText):
        # 遍历所有顶层项
        for i in range(treeWidget.topLevelItemCount()):  # 对于每个顶层项
            item = treeWidget.topLevelItem(i)  # 获取顶层项
            found = self.searchInItem(item, searchText)  # 在顶层项及其子项中搜索
            if found:  # 如果找到匹配项
                return found  # 返回找到的项

        return None  # 如果没有找到返回None

    def searchInItem(self, item, searchText):
        # 检查当前项
        if item.text(0).lower() == searchText:  # 如果找到完全匹配的项
            return item  # 返回找到的项

        # 遍历子项
        for i in range(item.childCount()):  # 对于每个子项
            childItem = item.child(i)  # 获取子项
            found = self.searchInItem(childItem, searchText)  # 在子项中递归搜索
            if found:  # 如果在子项中找到
                return found  # 返回找到的项

        return None  # 如果没有找到返回None

    def showError(self, message):
        # 显示错误消息框
        msgBox = QMessageBox()
        msgBox.setIcon(QMessageBox.Warning)
        msgBox.setText(message)
        msgBox.setWindowTitle("搜索错误")
        msgBox.setStandardButtons(QMessageBox.Ok)
        msgBox.exec_()  # 显示消息框并等待用户响应

    def closeEvent(self, event):
        result = QtWidgets.QMessageBox.question(self, "标题", "是否退出程序",
                                                QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
        if (result == QtWidgets.QMessageBox.Yes):
            if self.current_port and self.current_port.is_open:
                self.current_port.write(BRAIN_OXYGEN_CLOSE)
                self.current_port.write(EEG_CLOSE)
            event.accept()

        else:
            event.ignore()





    def next(self):
        self.ui.stackedWidget.setCurrentIndex(1)
        self.ui.label.setText('2')
        self.ui.next_btn.setEnabled(False)
        self.ui.pre_btn.setEnabled(True)

    def previous(self):
        self.ui.stackedWidget.setCurrentIndex(0)
        self.ui.label.setText('1')
        self.ui.next_btn.setEnabled(True)
        self.ui.pre_btn.setEnabled(False)

    def open_port(self):
        # if self.current_port is None:
        #     self.current_port = open_port()
        #     if self.current_port.is_open:
        #         self.ui.connect_btn.setEnabled(False)
        #         self.ui.close_btn.setEnabled(True)
        #         self.serial_handle_thread.start()
        #         self.serial_handle_thread.ser =self.current_port
        #         self.timer.start(1000)  #设置计时间隔并启动，每隔1000毫秒发送一次超时信号，循环进行
        # self.ui.connect_btn.setEnabled(False)
        # self.ui.close_btn.setEnabled(True)
        # self.timer.start(1000)
        # 点击连接后弹出串口选择对话框
        self.connect_dialog.show()
        self.hide()

    def close_port(self):
        if self.current_port is not None:
            if self.ui.EEG_close_btn.isEnabled() is True:
                self.current_port.write(EEG_CLOSE)
                self.ui.label_11.setText('状态：未连接')
                global sec2
                sec2 = 0
                self.timer2.stop()
                self.EEG_data_timer.stop()
                self.impedance_data_timer.stop()
                self.ui.label_12.setText('时间：' + str(sec2) + 's')
                self.ui.EEG_collect_btn.setEnabled(True)
                self.ui.EEG_close_btn.setEnabled(False)
            if self.ui.BO_close_btn.isEnabled() is True:
                self.current_port.write(BRAIN_OXYGEN_CLOSE)
                global sec1
                sec1 = 0
                global BO_i1
                BO_i1 = 0
                global BO_i2
                BO_i2 = 0
                self.BO_data_1 = np.zeros(20, dtype=float)
                self.BO_data_2 = np.zeros(20, dtype=float)
                self.timer1.stop()
                self.BO_data_1_timer.stop()
                self.BO_data_2_timer.stop()
                self.ui.label_10.setText('时间：' + str(sec1) + 's')
                self.ui.BO_collect_btn.setEnabled(True)
                self.ui.BO_close_btn.setEnabled(False)
                global BO_data1
                while not BO_data1.empty():
                    BO_data1.get()
                global BO_data2
                while not BO_data2.empty():
                    BO_data2.get()
            self.current_port.write(STIMULATION_CLOSE)
            self.ui.label_21.setText('状态：关闭')
            self.current_port.write(TDCS_RUN)
            self.ui.label_13.setText('状态：关闭')
            self.serial_read_thread.ser = None
            self.current_port.close()
            self.ui.connect_btn.setEnabled(True)
            self.ui.close_btn.setEnabled(False)
            self.current_port = None
            global sec
            sec = 0
            self.timer.stop()
            self.ui.connect_time_label.setText('已连接：' + str(sec) + '秒')



    def set_time(self):
        global sec
        sec += 1
        self.ui.connect_time_label.setText('已连接：' + str(sec) + '秒')

    def set_time1(self):
        global sec1
        sec1 += 1
        self.ui.label_10.setText('时间：' + str(sec1) + 's')

    def set_time2(self):
        global sec2
        sec2 += 1
        self.ui.label_12.setText('时间：' + str(sec2) + 's')

    #绘制脑氧数据波形
    def BO_plotData1(self):
        global BO_i1
        if not BO_data1.empty():
            if BO_i1 < 20:
                self.BO_data_1[BO_i1] = BO_data1.get()
                BO_i1 = BO_i1 + 1
            else:
                self.BO_data_1[:-1] = self.BO_data_1[1:]
                self.BO_data_1[BO_i1 - 1] = BO_data1.get()
            self.curve1.setData(self.BO_data_1)


    def BO_plotData2(self):
        global BO_i2
        if not BO_data2.empty():
            if BO_i2 < 20:
                self.BO_data_2[BO_i2] = BO_data2.get()
                BO_i2 = BO_i2 + 1
            else:
                self.BO_data_2[:-1] = self.BO_data_2[1:]
                self.BO_data_2[BO_i2 - 1] = BO_data2.get()
            self.curve2.setData(self.BO_data_2)

    def EEG_plotData2(self):
        self.EEG_curve1.setData(EEG_data_1)
        self.EEG_curve2.setData(EEG_data_2)
        self.EEG_curve3.setData(EEG_data_3)
        self.EEG_curve4.setData(EEG_data_4)
        self.EEG_curve5.setData(EEG_data_5)
        self.EEG_curve6.setData(EEG_data_6)
        self.EEG_curve7.setData(EEG_data_7)
        self.EEG_curve8.setData(EEG_data_8)


    def impedance_plotData2(self):
        self.impedance_curve1.setData(impedance_data_1)
        self.impedance_curve2.setData(impedance_data_2)
        self.impedance_curve3.setData(impedance_data_3)
        self.impedance_curve4.setData(impedance_data_4)
        self.impedance_curve5.setData(impedance_data_5)
        self.impedance_curve6.setData(impedance_data_6)
        self.impedance_curve7.setData(impedance_data_7)
        self.impedance_curve8.setData(impedance_data_8)


    #绘制脑电数据波形
    def EEG_plotData(self):
        start_time = time.time()
        global EEG_i1
        if not EEG_data.empty():
            if EEG_i1 < 1000:
                EEG_data_1[EEG_i1] = EEG_data.get()[0]
                EEG_data_2[EEG_i1] = EEG_data.get()[1]
                EEG_data_3[EEG_i1] = EEG_data.get()[2]
                EEG_data_4[EEG_i1] = EEG_data.get()[3]
                EEG_data_5[EEG_i1] = EEG_data.get()[4]
                EEG_data_6[EEG_i1] = EEG_data.get()[5]
                EEG_data_7[EEG_i1] = EEG_data.get()[6]
                EEG_data_8[EEG_i1] = EEG_data.get()[7]
                EEG_i1 = EEG_i1 + 1
            else:
                EEG_data_1[:-1] = EEG_data_1[1:]
                EEG_data_1[EEG_i1 - 1] = EEG_data.get()[0]
                EEG_data_2[:-1] = EEG_data_2[1:]
                EEG_data_2[EEG_i1 - 1] = EEG_data.get()[1]
                EEG_data_3[:-1] = EEG_data_3[1:]
                EEG_data_3[EEG_i1 - 1] = EEG_data.get()[2]
                EEG_data_4[:-1] = EEG_data_4[1:]
                EEG_data_4[EEG_i1 - 1] = EEG_data.get()[3]
                EEG_data_5[:-1] = EEG_data_5[1:]
                EEG_data_5[EEG_i1 - 1] = EEG_data.get()[4]
                EEG_data_6[:-1] = EEG_data_6[1:]
                EEG_data_6[EEG_i1 - 1] = EEG_data.get()[5]
                EEG_data_7[:-1] = EEG_data_7[1:]
                EEG_data_7[EEG_i1 - 1] = EEG_data.get()[6]
                EEG_data_8[:-1] = EEG_data_8[1:]
                EEG_data_8[EEG_i1 - 1] = EEG_data.get()[7]
            self.EEG_curve1.setData(EEG_data_1)
            self.EEG_curve2.setData(EEG_data_2)
            self.EEG_curve3.setData(EEG_data_3)
            self.EEG_curve4.setData(EEG_data_4)
            self.EEG_curve5.setData(EEG_data_5)
            self.EEG_curve6.setData(EEG_data_6)
            self.EEG_curve7.setData(EEG_data_7)
            self.EEG_curve8.setData(EEG_data_8)
        # global EEG_i2
        # if not EEG_data2.empty():
        #     if EEG_i2 < 1000:
        #         EEG_data_2[EEG_i2] = EEG_data2.get()
        #         EEG_i2 = EEG_i2 + 1
        #     else:
        #         EEG_data_2[:-1] = EEG_data_2[1:]
        #         EEG_data_2[EEG_i2 - 1] = EEG_data2.get()
        #     self.EEG_curve2.setData(EEG_data_2)
        # global EEG_i3
        # if not EEG_data3.empty():
        #     if EEG_i3 < 1000:
        #         EEG_data_3[EEG_i3] = EEG_data3.get()
        #         EEG_i3 = EEG_i3 + 1
        #     else:
        #         EEG_data_3[:-1] = EEG_data_3[1:]
        #         EEG_data_3[EEG_i3 - 1] = EEG_data3.get()
        #     self.EEG_curve3.setData(EEG_data_3)
        # global EEG_i4
        # if not EEG_data4.empty():
        #     if EEG_i4 < 1000:
        #         EEG_data_4[EEG_i4] = EEG_data4.get()
        #         EEG_i4 = EEG_i4 + 1
        #     else:
        #         EEG_data_4[:-1] = EEG_data_4[1:]
        #         EEG_data_4[EEG_i4 - 1] = EEG_data4.get()
        #     self.EEG_curve4.setData(EEG_data_4)
        # global EEG_i5
        # if not EEG_data5.empty():
        #     if EEG_i5 < 1000:
        #         EEG_data_5[EEG_i5] = EEG_data5.get()
        #         EEG_i5 = EEG_i5 + 1
        #     else:
        #         EEG_data_5[:-1] = EEG_data_5[1:]
        #         EEG_data_5[EEG_i5 - 1] = EEG_data5.get()
        #     self.EEG_curve5.setData(EEG_data_5)
        # global EEG_i6
        # if not EEG_data6.empty():
        #     if EEG_i6 < 1000:
        #         EEG_data_6[EEG_i6] = EEG_data6.get()
        #         EEG_i6 = EEG_i6 + 1
        #     else:
        #         EEG_data_6[:-1] = EEG_data_6[1:]
        #         EEG_data_6[EEG_i6 - 1] = EEG_data6.get()
        #     self.EEG_curve6.setData(EEG_data_6)
        # global EEG_i7
        # if not EEG_data7.empty():
        #     if EEG_i7 < 1000:
        #         EEG_data_7[EEG_i7] = EEG_data7.get()
        #         EEG_i7 = EEG_i7 + 1
        #     else:
        #         EEG_data_7[:-1] = EEG_data_7[1:]
        #         EEG_data_7[EEG_i7 - 1] = EEG_data7.get()
        #     self.EEG_curve7.setData(EEG_data_7)
        # global EEG_i8
        # if not EEG_data8.empty():
        #     if EEG_i8 < 1000:
        #         EEG_data_8[EEG_i8] = EEG_data8.get()
        #         EEG_i8 = EEG_i8 + 1
        #     else:
        #         EEG_data_8[:-1] = EEG_data_8[1:]
        #         EEG_data_8[EEG_i8 - 1] = EEG_data8.get()
        #     self.EEG_curve8.setData(EEG_data_8)
        end_time = time.time()  # 记录循环结束的时间
        print(f"绘图所用的时间: {end_time - start_time:.9f} 秒")  # 打印所用时间

    #绘制阻抗数据波形
    def impedance_plotData(self):
        global impedance_i1
        if not impedance_data1.empty():
            if impedance_i1 < 1000:
                impedance_data_1[impedance_i1] = impedance_data1.get()
                impedance_i1 = impedance_i1 + 1
            else:
                impedance_data_1[:-1] = impedance_data_1[1:]
                impedance_data_1[impedance_i1 - 1] = impedance_data1.get()
            self.impedance_curve1.setData(impedance_data_1)
        global impedance_i2
        if not impedance_data2.empty():
            if impedance_i2 < 1000:
                impedance_data_2[impedance_i2] = impedance_data2.get()
                impedance_i2 = impedance_i2 + 1
            else:
                impedance_data_2[:-1] = impedance_data_2[1:]
                impedance_data_2[impedance_i2 - 1] = impedance_data2.get()
            self.impedance_curve2.setData(impedance_data_2)
        global impedance_i3
        if not impedance_data3.empty():
            if impedance_i3 < 1000:
                impedance_data_3[impedance_i3] = impedance_data3.get()
                impedance_i3 = impedance_i3 + 1
            else:
                impedance_data_3[:-1] = impedance_data_3[1:]
                impedance_data_3[impedance_i3 - 1] = impedance_data3.get()
            self.impedance_curve3.setData(impedance_data_3)
        global impedance_i4
        if not impedance_data4.empty():
            if impedance_i4 < 1000:
                impedance_data_4[impedance_i4] = impedance_data4.get()
                impedance_i4 = impedance_i4 + 1
            else:
                impedance_data_4[:-1] = impedance_data_4[1:]
                impedance_data_4[impedance_i4 - 1] = impedance_data4.get()
            self.impedance_curve4.setData(impedance_data_4)
        global impedance_i5
        if not impedance_data5.empty():
            if impedance_i5 < 1000:
                impedance_data_5[impedance_i5] = impedance_data5.get()
                impedance_i5 = impedance_i5 + 1
            else:
                impedance_data_5[:-1] = impedance_data_5[1:]
                impedance_data_5[impedance_i5 - 1] = impedance_data5.get()
            self.impedance_curve5.setData(impedance_data_5)
        global impedance_i6
        if not impedance_data6.empty():
            if impedance_i6 < 1000:
                impedance_data_6[impedance_i6] = impedance_data6.get()
                impedance_i6 = impedance_i6 + 1
            else:
                impedance_data_6[:-1] = impedance_data_6[1:]
                impedance_data_6[impedance_i6 - 1] = impedance_data6.get()
            self.impedance_curve6.setData(impedance_data_6)
        global impedance_i7
        if not impedance_data7.empty():
            if impedance_i7 < 1000:
                impedance_data_7[impedance_i7] = impedance_data7.get()
                impedance_i7 = impedance_i7 + 1
            else:
                impedance_data_7[:-1] = impedance_data_7[1:]
                impedance_data_7[impedance_i7 - 1] = impedance_data7.get()
            self.impedance_curve7.setData(impedance_data_7)
        global impedance_i8
        if not impedance_data8.empty():
            if impedance_i8 < 1000:
                impedance_data_8[impedance_i8] = impedance_data8.get()
                impedance_i8 = impedance_i8 + 1
            else:
                impedance_data_8[:-1] = impedance_data_8[1:]
                impedance_data_8[impedance_i8 - 1] = impedance_data8.get()
            self.impedance_curve8.setData(impedance_data_8)




    # 连接对话框串口选择
    def back_confirm(self):
        if self.current_port is None:
            current_port_name = self.connect_dialog.comboBox.currentText()
            self.current_port = open_port(current_port_name)
            if self.current_port.is_open:
                self.ui.connect_btn.setEnabled(False)
                self.ui.close_btn.setEnabled(True)
                self.serial_handle_thread.start()
                # self.serial_read_thread_2.start()
                self.serial_read_thread.start()
                self.serial_read_thread.ser =self.current_port
                self.timer.start(1000)  #设置计时间隔并启动，每隔1000毫秒发送一次超时信号，循环进行
                self.current_port.write(BRAIN_OXYGEN_HANDSHAKE)
                time.sleep(1)
                self.current_port.write(TDCS_START)
                time.sleep(1)
                self.current_port.write(STIMULATION_OPEN)
                self.ui.label_21.setText('状态：已打开')
        self.connect_dialog.close()
        self.show()

    def back_cancel(self):
        self.connect_dialog.close()
        self.show()
#创建头部模型提示信息，点击OK
    def back_OK1(self):
        self.warning_t1.close()
        self.show()
    def back_OK2(self):
        self.warning_path.close()
        self.show()
    #点击脑电采集按钮
    def collect_EEG(self):
        if self.current_port is not  None and self.current_port.is_open:
            self.current_port.write(EEG_HANDSHAKE)
        else:
            result = QtWidgets.QMessageBox.question(self, "提示", "请先连接设备！",
                                                    QtWidgets.QMessageBox.Yes )


    def discollect_EEG(self):
        if self.current_port is not  None and self.current_port.is_open:
            self.current_port.write(EEG_CLOSE)
            self.ui.label_11.setText('状态：未连接')
            global sec2
            sec2 = 0
            self.timer2.stop()
            self.EEG_data_timer.stop()
            self.impedance_data_timer.stop()
            self.ui.label_12.setText('时间：' + str(sec2) + 's')
            self.ui.EEG_collect_btn.setEnabled(True)
            self.ui.EEG_close_btn.setEnabled(False)

    #收到脑电握手回复
    def EEG_connect(self):
        if self.current_port is not  None and self.current_port.is_open:
            self.ui.label_11.setText('状态：已连接')
            self.current_port.write(EEG_COLLECT)
            self.timer2.start(1000)
            self.EEG_data_timer.start(30)
            self.impedance_data_timer.start(30)
            # self.EEG_collect_thread.start()
            # self.impedance_collect_thread.start()
            self.ui.EEG_close_btn.setEnabled(True)
            self.ui.EEG_collect_btn.setEnabled(False)

    # 点击开始收集
    def collect_BO(self):
        if self.current_port is not  None and self.current_port.is_open:
            self.current_port.write(BRAIN_OXYGEN_COLLECT)
        else:
            result = QtWidgets.QMessageBox.question(self, "提示", "请先连接设备！",
                                                    QtWidgets.QMessageBox.Yes)

    def discollect_BO(self):
        if self.current_port.is_open:
            self.current_port.write(BRAIN_OXYGEN_CLOSE)

    # 采集指令得到回复开始发数据，开始计时
    def brain_oxygen_collect(self):
        if self.current_port is not  None and self.current_port.is_open:
            self.timer1.start(1000)
            self.BO_data_1_timer.start(50)
            self.BO_data_2_timer.start(50)
            self.ui.BO_collect_btn.setEnabled(False)
            self.ui.BO_close_btn.setEnabled(True)

    def brain_oxygen_discollect(self):
        global sec1
        sec1 = 0
        global BO_i1
        BO_i1 = 0
        global BO_i2
        BO_i2 = 0

        self.BO_data_1 = np.zeros(20, dtype=float)
        self.BO_data_2 = np.zeros(20, dtype=float)
        self.timer1.stop()
        self.BO_data_1_timer.stop()
        self.BO_data_2_timer.stop()
        self.ui.label_10.setText('时间：' + str(sec1) + 's')
        self.ui.BO_collect_btn.setEnabled(True)
        self.ui.BO_close_btn.setEnabled(False)
        global BO_data1
        while not BO_data1.empty():
            BO_data1.get()
        global BO_data2
        while not BO_data2.empty():
            BO_data2.get()

    # 握手上线程进行已连接
    def brain_oxygen_connect(self):
        self.ui.label_9.setText('状态：已连接')

    def brain_oxygen_disconnect(self):
        self.ui.label_9.setText('状态：未连接')

    # 点击连接按钮,收到确认回复后,tDCS模块状态显示已开机
    def tDCS_start(self):
        self.ui.label_13.setText('状态：已开机')
    def tDCS_error(self):
        self.ui.label_13.setText('状态：发生错误')

    def run_tDCS(self):
        if self.current_port.is_open:
            self.current_port.write(TDCS_RUN)

    def tDCS_run(self):

        self.timer3.start(1000)
        QMessageBox.information(self, "标题", "tDCS模块已启动")
        self.ui.pushButton.setEnabled(False)
        self.ui.pushButton_2.setEnabled(True)
        self.ui.pushButton_3.setEnabled(False)
         # 设置定时器间隔为1000毫秒（1秒）

    def stop_tDCS(self):
        if self.current_port.is_open:
            self.current_port.write(TDCS_RUN)


    def tDCS_stop(self):
        self.timer3.stop()
        self.ui.progressBar.setValue(0)
        self.ui.label_28.setText('0')
        self.ui.label_30.setText('0')
        QMessageBox.information(self, "标题", "tDCS模块已关闭")
        self.ui.pushButton.setEnabled(True)
        self.ui.pushButton_2.setEnabled(False)
        self.ui.pushButton_3.setEnabled(True)



    def updateProgressBarMax(self):
        self.ui.progressBar.setMaximum(int(self.ui.label_30.text()))

    def updateProgressBar(self):
        self.elapsedTime += 1  # 增加已过时间
        self.maxTime = int(self.ui.label_30.text())
        progress = self.elapsedTime / self.maxTime  # 计算进度
        self.ui.progressBar.setValue(int(progress * self.maxTime))  # 更新进度条的值
        if self.elapsedTime >= self.maxTime:
            self.timer3.stop()  # 停止定时器
            self.ui.progressBar.setValue(self.maxTime)  # 确保进度条满值


#     模式切换
    def alternating_current_mode(self):
        self.alternating_current_dialog.show()
        self.hide()
    def pulse_mode(self):
        self.pulse_dialog.show()
        self.hide()
    def confirm_alternating_current(self):
        if self.current_port.is_open:
            self.current_port.write(ALTERNATING_CURRENT)
            self.alternating_current_dialog.close()
            self.show()
            # print('11')
    def cancel_alternating_current(self):
        self.alternating_current_dialog.close()
        self.show()

    def confirm_pulse(self):
        if self.current_port.is_open:
            self.current_port.write(PULSE)
            self.pulse_dialog.close()
            self.show()

    def cancel_pulse(self):
        self.pulse_dialog.close()
        self.show()

    def direct_current_mode(self):
        if self.current_port.is_open:
            self.current_port.write(DIRECT_CURRENT)
    def pseudo_stimulus_mode(self):
        if self.current_port.is_open:
            self.current_port.write(PSEUDO_STIMULUS)
    def random_mode(self):
        if self.current_port.is_open:
            self.current_port.write(RANDOM)

    def increase_current(self):
        if self.current_port.is_open:
            self.current_port.write(CURRENT_INCREASE)
            current_text = self.ui.label_28.text()
            if int(current_text)>=0 and int(current_text)<2000:
                if int(current_text) >= 100:
                    new_value = int(current_text) + 100
                    if new_value > 2000:
                        new_value = 2000
                    self.ui.label_28.setText(str(new_value))

                if int(current_text) < 100:
                    new_value = int(current_text) + 10
                    self.ui.label_28.setText(str(new_value))

    def decrease_current(self):
        if self.current_port.is_open:
            self.current_port.write(CURRENT_DECREASE)
            current_text = self.ui.label_28.text()
            if int(current_text) > 0 and int(current_text) <= 2000:
                if int(current_text) > 100:
                    new_value = int(current_text) - 100
                    self.ui.label_28.setText(str(new_value))
                if int(current_text) <= 100:
                    new_value = int(current_text) - 10
                    if new_value < 0:
                        new_value = 0
                    self.ui.label_28.setText(str(new_value))

    def increase_time(self):
        if self.current_port.is_open:
            self.current_port.write(TIME_INCREASE)
            current_text = self.ui.label_30.text()
            if int(current_text) >= 0 and int(current_text) < 7200:
                new_value = int(current_text) + 300
                if new_value > 7200:
                    new_value = 7200
                self.ui.label_30.setText(str(new_value))

    def decrease_time(self):
        if self.current_port.is_open:
            self.current_port.write(TIME_DECREASE)
            current_text = self.ui.label_30.text()
            if int(current_text) > 0 and int(current_text) <= 7200:
                new_value = int(current_text) - 300
                if new_value < 0:
                    new_value = 0
                self.ui.label_30.setText(str(new_value))

    # 电流与时间自定义
    def set_current(self):
        if self.current_port.is_open:
            if self.ui.lineEdit.text():
                current = self.ui.lineEdit.text()
                current_value = int(current)
                print(hex(current_value))

                # 拆分为高位和低位字节
                high_byte = (current_value >> 8) & 0xFF  # 获取高位字节
                low_byte = current_value & 0xFF  # 获取低位字节
                CURRENT_SET = [0xAA,0x55,0x02,0x08,0x00,0x02,high_byte,low_byte,0x55]
                print('CURRENT_SET:',CURRENT_SET)

                # if current_value>=0 and current_value<=2000:
                if 0 <= current_value <= 2000:
                    self.ui.label_28.setText(current)
                    self.current_port.write(CURRENT_SET)

    def set_tDCS_time(self):
        if self.current_port.is_open:
            if self.ui.lineEdit_2.text():
                tDCS_time = self.ui.lineEdit_2.text()
                tDCS_time_value = int(tDCS_time)

                high_byte = (tDCS_time_value >> 8) & 0xFF  # 获取高位字节
                low_byte = tDCS_time_value & 0xFF  # 获取低位字节

                TIME_SET = [0xAA,0x55,0x02,0x08,0x00,0x04, high_byte,low_byte,0x55]
                print('TIME_SET:', TIME_SET)

                # if int(tDCS_time )>=1 and int(tDCS_time )<=7200:
                if 1 <= tDCS_time_value <= 7200:
                    self.ui.label_30.setText(tDCS_time)
                    self.current_port.write(TIME_SET)

    # 光刺激模块
    # 启动与关闭设置
    def run_stimulation(self):
        if self.current_port.is_open:
            self.current_port.write(STIMULATION_RUN)
            time.sleep(1)
            if self.ui.radioButton_10.isChecked()+self.ui.radioButton_11.isChecked()+self.ui.radioButton_12.isChecked()+self.ui.radioButton_13.isChecked()+self.ui.radioButton_38.isChecked() > 0:
                flag1 = 1;
            else :
                flag1 = 0;
            if self.ui.radioButton_14.isChecked()+self.ui.radioButton_20.isChecked()+self.ui.radioButton_25.isChecked()+self.ui.radioButton_31.isChecked()+self.ui.radioButton_39.isChecked() >0:
                flag2 = 1;
            else:
                flag2 = 0;

            self.current_port.write([0xAA,0x55,0x04,0x06,0x0c,int(flag1+flag2),0x55])




    def prompt_stimulation_run(self):
        QMessageBox.information(self, "标题", "光刺激模块已启动")  # 最后的Yes表示弹框的按钮显示为Yes，默认按钮显示为OK,不填QMessageBox.Yes即为默认
        self.ui.pushButton_4.setEnabled(False)
        self.ui.pushButton_5.setEnabled(True)

    def stop_stimulation(self):
        if self.current_port.is_open:
            self.current_port.write(STIMULATION_STOP)

    def prompt_simulation_stop(self):
        QMessageBox.information(self, "标题", "光刺激模块已停止运行")
        self.ui.label_43.setText('0')

        self.ui.pushButton_4.setEnabled(True)
        self.ui.pushButton_5.setEnabled(False)

    # 重置模块参数
    def reset_stimulation(self):
        if self.current_port.is_open:
            self.current_port.write(STIMULATION_RESET)
            # self.ui.radioButton_7.setChecked(True)
            # self.ui.radioButton_12.setChecked(True)
            # self.ui.radioButton_18.setChecked(True)
            # self.ui.radioButton_25.setChecked(True)
            # self.ui.radioButton_36.setChecked(True)

    def reset_stimulation_parameter(self):
        self.ui.radioButton_7.setChecked(True)
        self.ui.radioButton_12.setChecked(True)
        self.ui.radioButton_18.setChecked(True)
        self.ui.radioButton_25.setChecked(True)
        self.ui.radioButton_36.setChecked(True)
        self.ui.label_43.setText("720")
        self.current_port.write([0xAA, 0x55, 0x04, 0x06, 0x54, 0x0C, 0x55])
        time.sleep(1)
        self.current_port.write([0xAA, 0x55, 0x04, 0x06, 0x1F, 0x28, 0x55])
        time.sleep(1)
        self.current_port.write([0xAA, 0x55, 0x04, 0x06, 0x2F, 0x28, 0x55])
        time.sleep(1)
        self.current_port.write([0xAA, 0x55, 0x04, 0x06, 0x1e, 0x33, 0x55])
        time.sleep(1)
        self.current_port.write([0xAA, 0x55, 0x04, 0x06, 0x2e, 0x33, 0x55])





    # 设置刺激时间
    def set_stimulation_time(self):
        if self.current_port.is_open:
            if self.ui.radioButton_6.isChecked():
                self.STIMULATION_TIME_SET = [0xAA, 0x55, 0x04, 0x06, 0x54, 0x05, 0x55]
                self.ui.label_43.setText("300")
            elif self.ui.radioButton_7.isChecked():
                self.STIMULATION_TIME_SET = [0xAA, 0x55, 0x04, 0x06, 0x54, 0x0C, 0x55]
                self.ui.label_43.setText("720")
            elif self.ui.radioButton_8.isChecked():
                self.STIMULATION_TIME_SET = [0xAA, 0x55, 0x04, 0x06, 0x54, 0x14, 0x55]
                self.ui.label_43.setText("1200")
            elif self.ui.radioButton_9.isChecked():
                self.defined_time = self.ui.lineEdit_7.text()
                if self.defined_time:
                    if int(self.defined_time) > 0 and int(self.defined_time) <= 99:
                        self.STIMULATION_TIME_SET = [0xAA, 0x55, 0x04, 0x06, 0x54, int(self.defined_time), 0x55]
                        self.ui.label_43.setText(str(int(self.defined_time)*60))
                    else:
                        self.STIMULATION_TIME_SET = []
                        QMessageBox.information(self, "标题", "数据范围0-99")

                else:
                    self.STIMULATION_TIME_SET=[]
                    QMessageBox.information(self, "标题", "请先输入数据")
                    self.ui.radioButton_9.setAutoExclusive(False)
                    self.ui.radioButton_9.setChecked(False)
                    self.ui.radioButton_9.setAutoExclusive(True)

            print(self.STIMULATION_TIME_SET)
            print(self.ui.radioButton_6.isChecked())
            print(self.ui.radioButton_7.isChecked())
            print(self.ui.radioButton_8.isChecked())
            print(self.ui.radioButton_9.isChecked())
            self.current_port.write(self.STIMULATION_TIME_SET)

    # 设置刺激频率
    def set_stimulation_frequency1(self):
        if self.current_port.is_open:
            if self.ui.radioButton_10.isChecked():
                self.STIMULATION_FREQUENCY_SET = [0xAA,0x55,0x04,0x06,0x1F,0x00,0x55]
            elif self.ui.radioButton_11.isChecked():
                self.STIMULATION_FREQUENCY_SET = [0xAA,0x55,0x04,0x06,0x1F,0x0A,0x55]
            elif self.ui.radioButton_12.isChecked():
                self.STIMULATION_FREQUENCY_SET = [0xAA, 0x55, 0x04, 0x06, 0x1F, 0x28, 0x55]
            elif self.ui.radioButton_13.isChecked():
                self.STIMULATION_FREQUENCY_SET = [0xAA, 0x55, 0x04, 0x06, 0x1F, 0x63, 0x55]
            elif self.ui.radioButton_38.isChecked():
                self.defined_frequency = self.ui.lineEdit_8.text()
                if self.defined_frequency:
                    if int(self.defined_frequency) > 0 and int(self.defined_frequency) <= 99:
                        self.STIMULATION_FREQUENCY_SET = [0xAA, 0x55, 0x04, 0x06, 0x1F, int(self.defined_frequency), 0x55]
                    else:
                        self.STIMULATION_FREQUENCY_SET = []
                        QMessageBox.information(self, "标题", "数据范围0-99")
                else:
                    self.STIMULATION_FREQUENCY_SET=[]
                    QMessageBox.information(self, "标题", "请先输入数据")
                    self.ui.radioButton_38.setAutoExclusive(False)
                    self.ui.radioButton_38.setChecked(False)
                    self.ui.radioButton_38.setAutoExclusive(True)
            self.current_port.write(self.STIMULATION_FREQUENCY_SET)
            print(self.STIMULATION_FREQUENCY_SET)

    def set_stimulation_frequency2(self):
        if self.current_port.is_open:
            if self.ui.radioButton_14.isChecked():
                self.STIMULATION_FREQUENCY_SET = [0xAA,0x55,0x04,0x06,0x2F,0x00,0x55]
            elif self.ui.radioButton_20.isChecked():
                self.STIMULATION_FREQUENCY_SET = [0xAA,0x55,0x04,0x06,0x2F,0x0A,0x55]
            elif self.ui.radioButton_25.isChecked():
                self.STIMULATION_FREQUENCY_SET = [0xAA, 0x55, 0x04, 0x06, 0x2F, 0x28, 0x55]
            elif self.ui.radioButton_31.isChecked():
                self.STIMULATION_FREQUENCY_SET = [0xAA, 0x55, 0x04, 0x06, 0x2F, 0x63, 0x55]
            elif self.ui.radioButton_39.isChecked():
                self.defined_frequency = self.ui.lineEdit_9.text()
                if self.defined_frequency:
                    if int(self.defined_frequency) > 0 and int(self.defined_frequency) <= 99:
                        self.STIMULATION_FREQUENCY_SET = [0xAA, 0x55, 0x04, 0x06, 0x2F, int(self.defined_frequency), 0x55]
                    else:
                        self.STIMULATION_FREQUENCY_SET = []
                        QMessageBox.information(self, "标题", "数据范围0-99")
                else:
                    self.STIMULATION_FREQUENCY_SET = []
                    QMessageBox.information(self, "标题", "请先输入数据")
                    self.ui.radioButton_39.setAutoExclusive(False)
                    self.ui.radioButton_39.setChecked(False)
                    self.ui.radioButton_39.setAutoExclusive(True)
            print(self.STIMULATION_FREQUENCY_SET)

    # 设置辐照度
    def set_stimulation_irradiance1(self):
        if self.current_port.is_open:
            if self.ui.radioButton_15.isChecked():
                self.STIMULATION_IRRADIANCE_SET = [0xAA,0x55,0x04,0x06,0x1e,0x18,0x55]
            elif self.ui.radioButton_16.isChecked():
                self.STIMULATION_IRRADIANCE_SET = [0xAA, 0x55, 0x04, 0x06, 0x1e, 0x21, 0x55]
            elif self.ui.radioButton_17.isChecked():
                self.STIMULATION_IRRADIANCE_SET = [0xAA, 0x55, 0x04, 0x06, 0x1e, 0x2a, 0x55]
            elif self.ui.radioButton_18.isChecked():
                self.STIMULATION_IRRADIANCE_SET = [0xAA, 0x55, 0x04, 0x06, 0x1e, 0x33, 0x55]
            elif self.ui.radioButton_19.isChecked():
                self.STIMULATION_IRRADIANCE_SET = [0xAA, 0x55, 0x04, 0x06, 0x1e, 0x3C, 0x55]
            elif self.ui.radioButton_40.isChecked():
                self.defined_irradiance = self.ui.lineEdit_10.text()
                if self.defined_irradiance:
                    if int(self.defined_irradiance) > 400:
                        self.STIMULATION_IRRADIANCE_SET = [0xAA, 0x55, 0x04, 0x06, 0x1e, int(0.24*int(self.defined_irradiance)-26), 0x55]
                    elif int(self.defined_irradiance) <= 400:
                        self.STIMULATION_IRRADIANCE_SET = [0xAA, 0x55, 0x04, 0x06, 0x1e,
                                                           int(0.18 * int(self.defined_irradiance) - 3), 0x55]
                else:
                    self.STIMULATION_IRRADIANCE_SET=[]
                    QMessageBox.information(self, "标题", "请先输入数据")
                    self.ui.radioButton_40.setAutoExclusive(False)
                    self.ui.radioButton_40.setChecked(False)
                    self.ui.radioButton_40.setAutoExclusive(True)

            self.current_port.write(self.STIMULATION_IRRADIANCE_SET)
            print(self.STIMULATION_IRRADIANCE_SET)

    def set_stimulation_irradiance2(self):
        if self.current_port.is_open:
            if self.ui.radioButton_33.isChecked():
                self.STIMULATION_IRRADIANCE_SET = [0xAA, 0x55, 0x04, 0x06, 0x2e, 0x18, 0x55]
            elif self.ui.radioButton_34.isChecked():
                self.STIMULATION_IRRADIANCE_SET = [0xAA, 0x55, 0x04, 0x06, 0x2e, 0x21, 0x55]
            elif self.ui.radioButton_35.isChecked():
                self.STIMULATION_IRRADIANCE_SET = [0xAA, 0x55, 0x04, 0x06, 0x2e, 0x2a, 0x55]
            elif self.ui.radioButton_36.isChecked():
                self.STIMULATION_IRRADIANCE_SET = [0xAA, 0x55, 0x04, 0x06, 0x2e, 0x33, 0x55]
            elif self.ui.radioButton_37.isChecked():
                self.STIMULATION_IRRADIANCE_SET = [0xAA, 0x55, 0x04, 0x06, 0x2e, 0x3C, 0x55]
            elif self.ui.radioButton_41.isChecked():
                self.defined_irradiance = self.ui.lineEdit_11.text()
                if self.defined_irradiance:
                    if int(self.defined_irradiance) > 400:
                        self.STIMULATION_IRRADIANCE_SET = [0xAA, 0x55, 0x04, 0x06, 0x2e,
                                                           int(0.24 * int(self.defined_irradiance) - 26), 0x55]
                    elif int(self.defined_irradiance) <= 400:
                        self.STIMULATION_IRRADIANCE_SET = [0xAA, 0x55, 0x04, 0x06, 0x2e,
                                                           int(0.18 * int(self.defined_irradiance) - 3), 0x55]
                else:
                    self.STIMULATION_IRRADIANCE_SET = []
                    QMessageBox.information(self, "标题", "请先输入数据")
                    self.ui.radioButton_41.setAutoExclusive(False)
                    self.ui.radioButton_41.setChecked(False)
                    self.ui.radioButton_41.setAutoExclusive(True)
            self.current_port.write(self.STIMULATION_IRRADIANCE_SET)
            print(self.STIMULATION_IRRADIANCE_SET)


#张子旭的函数
    def show_second_page(self):
        self.ui.stackedWidget_5.setCurrentIndex(2)
    def show_first_page(self):
        self.ui.stackedWidget_5.setCurrentIndex(0)
    def show_1_page(self):
        self.ui.stackedWidget_5.setCurrentIndex(1)
    def pickAshow8(self):
        filename,filetype = QtWidgets.QFileDialog.getOpenFileName(None, "选取python文件", "C:/")  # 起始路径

    def writeToExcelsheet1(self):
        name = self.build_electrode.lineEdit.text()
        path = self.build_electrode.lineEdit_6.text()
        path_2 = self.build_electrode.lineEdit_2.text()
        if name and path and path_2:  # 检查都不为空
            # 如果两个变量都不为空，执行后续代码
            group = self.build_electrode.comboBox.currentText()  # 获取当前选中的分组
            # headModule_path = 'path/to/your/excel/'  # 替换为你的路径
            filename = 'data_log.xlsx'
            full_path = os.path.join(headModule_path, filename)


            try:
                workbook = openpyxl.load_workbook(full_path)
                sheet = workbook['电极仿真']

            except FileNotFoundError:
                QMessageBox.critical(self, 'Error', 'The file was not found.')
            except InvalidFileException:
                QMessageBox.critical(self, 'Error', 'The file is not a valid Excel file.')
            else:
                next_row = sheet.max_row + 1
                sheet.cell(row=next_row, column=1, value=name)
                sheet.cell(row=next_row, column=2, value=path)
                sheet.cell(row=next_row, column=3, value=group)
                workbook.save(full_path)

                # 清空 lineEdit 和 lineEdit_6
                self.build_electrode.lineEdit.clear()
                self.build_electrode.lineEdit_6.clear()
                print(f"Saving to: {full_path}")
                self.build_electrode.close()
                tdcs_run_simulation(headModule_path, pathfem=path, input_dicts=None, csv_path=path_2)
                QMessageBox.information(self, 'Success', '创建成功!')
                self.updateTreeWidget(full_path, workbook['电极仿真'], self.ui.treeWidget)

                self.show()
        else:
            # 如果name或path为空，执行错误处理
            QMessageBox.information(self, '错误', '请填写完整信息！')

    def writeToExcelsheet2(self):
        name = self.build_light.lineEdit.text()
        spath = self.build_light.lineEdit_6.text()
        region= self.build_light.lineEdit_2.text()
        p=self.build_light.lineEdit_3.text()
        t=self.build_light.lineEdit_4.text()
        wave = self.build_light.comboBox_2.currentText()
        if name and spath and region and p and t:  # 检查都不为空
            # 如果两个变量都不为空，执行后续代码
            group = self.build_light.comboBox.currentText()  # 获取当前选中的分组
            # headModule_path = 'path/to/your/excel/'  # 替换为你的路径
            filename = 'data_log.xlsx'
            full_path = os.path.join(headModule_path, filename)

            try:
                workbook = openpyxl.load_workbook(full_path)
                sheet = workbook['光源仿真']

            except FileNotFoundError:
                QMessageBox.critical(self, 'Error', 'The file was not found.')
            except InvalidFileException:
                QMessageBox.critical(self, 'Error', 'The file is not a valid Excel file.')
            else:
                next_row = sheet.max_row + 1
                sheet.cell(row=next_row, column=1, value=name)
                sheet.cell(row=next_row, column=2, value=spath)
                sheet.cell(row=next_row, column=3, value=group)
                workbook.save(full_path)

                # 清空 lineEdit 和 lineEdit_6
                self.build_light.lineEdit.clear()
                self.build_light.lineEdit_6.clear()

                print(f"Saving to: {full_path}")
                self.build_light.close()
                subject_path = headModule_path
                p = float(p)
                t = float(t)
                region_name = region
                save_path = spath
                wavelength = wave  # 获取波长参数

                input_dict = {
                    "path": os.path.join(subject_path, "final_tissues.nii.gz"),
                    "subject_csv": os.path.join(subject_path, "eeg_positions", "EEG10-10_UI_Jurak_2007.csv"),
                    "seg_path": None,
                    "region_name": region_name,
                    "src_dir_mode": "default",
                }
                output_dict = run_fn(input_dict)
                vol = output_dict["vol"]
                src_dir = output_dict["src_dir"]
                src_pos = output_dict["src_pos"]
                output_dict["stage_2_mode"] = "full"
                output_dict["custom_src"] = None
                output_dict["save_path"] = save_path
                output_dict["p"] = p
                output_dict["t"] = t
                output_dict["wavelength"] = wavelength  # 添加波长参数到输出字典
                output_dict["path"] = input_dict["path"]
                output_dict_2 = run_fn_stage2(output_dict)

                QMessageBox.information(self, 'Success', '创建成功!')
                self.updateTreeWidget(full_path, workbook['光源仿真'], self.ui.treeWidget_3)

                self.show()
        else:
            # 如果name或path为空，执行错误处理
            QMessageBox.information(self, '错误', '请填写完整信息！')

    # def writeToExcelsheet3(self):
    #     name = self.build_light.lineEdit.text()
    #     path = self.build_light.lineEdit_6.text()
    #     group = self.build_light.comboBox.currentText()  # 获取当前选中的分组
    #     # headModule_path = 'path/to/your/excel/'  # 替换为你的路径
    #     filename = 'data_log.xlsx'
    #     full_path = os.path.join(headModule_path, filename)
    #
    #     try:
    #         workbook = openpyxl.load_workbook(full_path)
    #         sheet = workbook['光源仿真']
    #
    #     except FileNotFoundError:
    #         QMessageBox.critical(self, 'Error', 'The file was not found.')
    #     except InvalidFileException:
    #         QMessageBox.critical(self, 'Error', 'The file is not a valid Excel file.')
    #     else:
    #         next_row = sheet.max_row + 1
    #         sheet.cell(row=next_row, column=1, value=name)
    #         sheet.cell(row=next_row, column=2, value=path)
    #         sheet.cell(row=next_row, column=3, value=group)
    #         workbook.save(full_path)
    #
    #         # 清空 lineEdit 和 lineEdit_6
    #         self.build_light.lineEdit.clear()
    #         self.build_light.lineEdit_6.clear()
    #
    #         print(f"Saving to: {full_path}")
    #         print(f"Writing to row {next_row}: name={name}, path={path}")
    #         QMessageBox.information(self, 'Success', '创建成功!')
    #         self.updateTreeWidget(full_path, workbook['光源仿真'], self.ui.treeWidget_3)


    def updateTreeWidget(self, full_path, sheet, treeWidget):
        try:
            workbook = load_workbook(full_path)
            # 假设name列在A列，group列在C列（第三列）
            names = [cell.value for cell in sheet['A']]
            print(names)
            groups = [cell.value for cell in sheet['C']]
            print(groups)
            # 清空现有的treeWidget
            treeWidget.clear()
            # 创建一个字典来存储分组和对应的项
            group_dict = {}
            for name, group in zip(names[1:], groups[1:]):  # 从第二项开始迭代
                if name is not None and group is not None:  # 避免添加空值
                    if group not in group_dict:
                        group_dict[group] = []
                    group_dict[group].append(name)
            # 遍历分组字典，创建分组和子项
            for group, items in group_dict.items():
                group_item = QTreeWidgetItem([group])  # 创建分组项
                for item in items:
                    child_item = QTreeWidgetItem([item])  # 创建子项
                    group_item.addChild(child_item)  # 将子项添加到分组项下
                treeWidget.addTopLevelItem(group_item)  # 将分组项添加到treeWidget
        except Exception as e:
            QMessageBox.critical(self, 'Error', str(e))


    def createGroup1(self):
        # 获取新分组的名称
        groupName, ok = QInputDialog.getText(self, '新建分组', '请输入分组名称:')
        if ok and groupName:
            groupItem = QTreeWidgetItem([groupName])
            self.ui.treeWidget.addTopLevelItem(groupItem)
            groupItem.setExpanded(True)

    def createGroup2(self):
        # 获取新分组的名称
        groupName, ok = QInputDialog.getText(self, '新建分组', '请输入分组名称:')
        if ok and groupName:
            groupItem = QTreeWidgetItem([groupName])
            self.ui.treeWidget_3.addTopLevelItem(groupItem)
            groupItem.setExpanded(True)
    def createGroup3(self):
        # 获取新分组的名称
        groupName, ok = QInputDialog.getText(self, '新建分组', '请输入分组名称:')
        if ok and groupName:
            groupItem = QTreeWidgetItem([groupName])
            self.ui.treeWidget_2.addTopLevelItem(groupItem)
            groupItem.setExpanded(True)

    def dropEvent(self, event):
        if event.dropAction() == Qt.MoveAction:
            sourceItem = event.source().currentItem()
            targetItem = self.ui.treeWidget.itemAt(event.pos())
            # print(sourceItem)
            # print(targetItem)

            # 检查 targetItem 是否为顶层项
            if sourceItem and targetItem and targetItem.parent() is None:
                # 执行剪操作
                sourceItem.parent().removeChild(sourceItem)
                targetItem.addChild(sourceItem)
                self.updateExcel(self.ui.treeWidget,  '电极仿真')
                print("1")

            else:
                QMessageBox.warning(self, '错误', '只能将项目拖动到父级分组')
    def dropEvent_2(self, event):
        if event.dropAction() == Qt.MoveAction:
            sourceItem = event.source().currentItem()
            targetItem = self.ui.treeWidget_2.itemAt(event.pos())
            print(sourceItem)
            print(targetItem)

            # 检查 targetItem 是否为顶层项
            if sourceItem and targetItem and targetItem.parent() is None:
                # 执行剪操作
                sourceItem.parent().removeChild(sourceItem)
                targetItem.addChild(sourceItem)
                self.updateExcel(self.ui.treeWidget_2,  '优化配置')

            else:
                QMessageBox.warning(self, '错误', '只能将项目拖动到父级分组')
    def dropEvent_3(self, event):
        if event.dropAction() == Qt.MoveAction:
            sourceItem = event.source().currentItem()
            targetItem = self.ui.treeWidget_3.itemAt(event.pos())
            print(sourceItem)
            print(targetItem)

            # 检查 targetItem 是否为顶层项
            if sourceItem and targetItem and targetItem.parent() is None:
                # 执行剪操作
                sourceItem.parent().removeChild(sourceItem)
                targetItem.addChild(sourceItem)
                self.updateExcel(self.ui.treeWidget_3,  '光源仿真')

            else:
                QMessageBox.warning(self, '错误', '只能将项目拖动到父级分组')

    def on_delete_clicked(self, treeWidget, sheet):
        # 获取当前选中的项
        selected_items = treeWidget.selectedItems()
        if not selected_items:
            return  # 如果没有选中的项，则不执行任何操作

        # 删除选中的项及其直接子项
        for item in selected_items:
            # 如果是顶层项，删除它及其所有直接子项
            if item.parent() is None:
                # 先删除所有直接子项
                while item.childCount() > 0:
                    child_item = item.child(0)  # 获取第一个子项
                    item.removeChild(child_item)  # 删除子项
                # 删除顶层项本身
                treeWidget.takeTopLevelItem(treeWidget.indexOfTopLevelItem(item))
            else:  # 如果是子项，直接删除
                item.parent().removeChild(item)

        # 更新Excel文件
        self.deleteExcel(treeWidget, sheet)

    def deleteExcel(self, treeWidget, sheetName):
        # 打开现有的 Excel 工作簿
        filename = 'data_log.xlsx'
        full_path = os.path.join(headModule_path, filename)
        workbook = openpyxl.load_workbook(full_path)
        sheet = workbook[sheetName]

        # 获取treeWidget中所有顶层项和子项的名称
        tree_names = set()
        for item in treeWidget.findItems("", Qt.MatchContains | Qt.MatchRecursive):
            tree_names.add(item.text(0))

        # 遍历Excel中的所有行，从第二行开始
        for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row):
            name = row[0].value  # 名称在第一列
            if name is not None and name not in tree_names:
                # 如果Excel中的名称不在treeWidget中，删除该行
                sheet.delete_rows(row[0].row)

        # 保存更新后的 Excel 文件
        workbook.save(full_path)
    def updateExcel(self, treeWidget, sheetName):
        # 打开现有的 Excel 工作簿
        filename = 'data_log.xlsx'
        full_path = os.path.join(headModule_path, filename)
        workbook = openpyxl.load_workbook(full_path)
        sheet = workbook[sheetName]

        # 遍历 treeWidget 中的所有顶层项（父级分组）
        for i in range(treeWidget.topLevelItemCount()):
            parentItem = treeWidget.topLevelItem(i)
            group = parentItem.text(0)  # 获取父级分组的文本作为分组信息

            # 遍历父级分组下的所有子项
            for j in range(parentItem.childCount()):
                childItem = parentItem.child(j)
                name = childItem.text(0)  # 获取子项的文本作为名称

                # 找到项在 Excel 中的行号
                row = next(
                    (r for r, cell in enumerate(sheet.iter_rows(min_row=2, values_only=True)) if cell[0] == name), None)

                if row is not None:  # 如果项在 Excel 中，更新分组信息
                    sheet.cell(row=row+2, column=3, value=group)  # 分组信息在第三列
                else:
                    print(f"Warning: Item '{name}' not found in Excel sheet.")

        # 保存更新后的 Excel 文件
        workbook.save(full_path)
    #查看头部模型
    def call_show_mesh(self):
        self.hide()
        files = os.listdir(headModule_path)
        # 过滤出.msh文件
        msh_files = [file for file in files if file.endswith('.msh')]
        if not msh_files:
            # 如果没有.msh文件，弹出错误窗口
            QMessageBox.warning(self, '错误', 'No .msh files found in the directory.')
        else:
            # 如果有.msh文件，返回第一个.msh文件的完整路径
            print("here", msh_files)
            full_path = os.path.join(headModule_path, msh_files[0])
        print(f"The full path to the .msh file is: {full_path}")
        showmsh(full_path)
        self.show()

    # 查看T1、T2
    def call_show_T1(self):
        self.hide()
        # 列出目录下的所有文件
        files = os.listdir(headModule_path)
        # 过滤出.msh文件
        _files = 'T1.nii.gz'
        if _files not in files:
            # 如果没有.msh文件，弹出错误窗口
            QMessageBox.warning(self, '错误', 'No .msh files found in the directory.')
        else:
            # 如果有.msh文件，返回第一个.msh文件的完整路径
            full_path = os.path.join(headModule_path, _files)
        print(f"The full path to the .msh file is: {full_path}")
        open_itk_snap(full_path)
        self.show()
    def call_show_T2(self):
        self.hide()
        # 列出目录下的所有文件
        files = os.listdir(headModule_path)
        # 过滤出.msh文件
        _files = 'T2_reg.nii.gz'
        if _files not in files:
            # 如果没有.msh文件，弹出错误窗口
            QMessageBox.warning(self, '错误', 'No .msh files found in the directory.')
        else:
            # 如果有.msh文件，返回第一个.msh文件的完整路径
            full_path = os.path.join(headModule_path, _files)
        print(f"The full path to the .msh file is: {full_path}")
        open_itk_snap(full_path)
        self.show()

    def call_show_cond(self, output_path=None):
        self.hide()
        # parser = argparse.ArgumentParser(description="Process FEM anisotropy types and export results to NIfTI")
        # parser.add_argument('--subpath', required=True, help="Path to the subject folder (e.g., 'm2m_ernie')")
        # parser.add_argument('--output_path', help="Optional: Output file path for the NIfTI file")
        # args = parser.parse_args()
        # Process anisotropy types in a loop
        for types in ["scalar", "vn", "dir", "mc"]:
            cond_file_path = os.path.join(headModule_path, "cond_file", f"cond_result_{types}.nii.gz")

            # Check if the file already exists
            if os.path.exists(cond_file_path):
                print(f"File {cond_file_path} already exists. Opening in ITK-SNAP...")
                open_itk_snap_cond(cond_file_path)
            else:
                print(
                    f"File {cond_file_path} does not exist. Generating visualization results for {types} anisotropy...")
                process_anisotropy_type(types, headModule_path)
                open_itk_snap_cond(cond_file_path)
        self.show()

    def open_e(self):
        filename = 'data_log.xlsx'
        full_path = os.path.join(headModule_path, filename)
        workbook = openpyxl.load_workbook(full_path)
        sheet = workbook['电极仿真']
        selected_items = self.ui.treeWidget.selectedItems()
        for item in selected_items:
            print('select', item.text(0))
        found_value = None
        if not selected_items:
            QMessageBox.warning(self, '错误', '请选择要打开的文件')
        for item in selected_items:
            if item.parent() is None:
                QMessageBox.warning(self, '错误', '请选择文件而不是分组')
            else:
                for row in sheet.iter_rows(min_row=2, max_col=2):  # 假设第一行是标题行，从第二行开始查找
                    for item in selected_items:
                        selected=item.text(0)
                    if row[0].value == selected:  # 第一列的值与selected_item匹配
                        found_value = row[1].value  # 将对应的第二列的值赋给found_value
                        break  # 找到匹配项后退出循环
                    # 现在found_value变量中包含了找到的第二列的值
                if found_value is not None:
                    print(f"Found value for {selected}: {found_value}")
                    files = os.listdir(found_value)
                    # 过滤出.msh文件
                    msh_files = [file for file in files if file.endswith('.msh')]
                    if not msh_files:
                        # 如果没有.msh文件，弹出错误窗口
                        QMessageBox.warning(self, '错误', 'No .msh files found in the directory.')
                    else:
                        # 如果有.msh文件，返回第一个.msh文件的完整路径
                        print("here", msh_files)
                        full_p = os.path.join(found_value, msh_files[0])
                        print(f"The full path to the .msh file is: {full_p}")
                        self.hide()
                        showmsh(full_p)

                else:
                    print(f"No value found for {selected}")
                    QMessageBox.warning(self, '错误', '找不到该文件地址，请重新创建!')
        self.show()
    def open_l(self):
        filename = 'data_log.xlsx'
        full_path = os.path.join(headModule_path, filename)
        workbook = openpyxl.load_workbook(full_path)
        sheet = workbook['光源仿真']
        selected_items = self.ui.treeWidget_3.selectedItems()
        for item in selected_items:
            print('select', item.text(0))
        found_value = None
        if not selected_items:
            QMessageBox.warning(self, '错误', '请选择要打开的文件')
        for item in selected_items:
            if item.parent() is None:
                QMessageBox.warning(self, '错误', '请选择文件而不是分组')
            else:
                for row in sheet.iter_rows(min_row=2, max_col=2):  # 假设第一行是标题行，从第二行开始查找
                    for item in selected_items:
                        selected = item.text(0)
                    if row[0].value == selected:  # 第一列的值与selected_item匹配
                        found_value = row[1].value  # 将对应的第二列的值赋给found_value
                        break  # 找到匹配项后退出循环
                    # 现在found_value变量中包含了找到的第二列的值
                if found_value is not None:
                    print(f"Found value for {selected}: {found_value}")
                    files = os.listdir(found_value)
                    # 过滤出.msh文件
                    _files = 'MCX_results_log.nii.gz'
                    if _files not in files:
                        # 如果没有.msh文件，弹出错误窗口
                        QMessageBox.warning(self, '错误', 'No .msh files found in the directory.')
                    else:
                        # 如果有.msh文件，返回第一个.msh文件的完整路径
                        full_p = os.path.join(found_value, _files)

                        print(f"The full path to the .msh file is: {full_p}")
                        self.hide()
                        open_itk_snap(full_p)

                else:
                    print(f"No value found for {selected}")
                    QMessageBox.warning(self, '错误', '找不到该文件地址，请重新创建!')
        self.show()
    def open_y(self):
        filename = 'data_log.xlsx'
        full_path = os.path.join(headModule_path, filename)
        workbook = openpyxl.load_workbook(full_path)
        sheet = workbook['优化配置']
        selected_items = self.ui.treeWidget_2.selectedItems()
        for item in selected_items:
            print('select', item.text(0))
        found_value = None
        if not selected_items:
            QMessageBox.warning(self, '错误', '请选择要打开的文件')
        for item in selected_items:
            if item.parent() is None:
                QMessageBox.warning(self, '错误', '请选择文件而不是分组')
            else:
                for row in sheet.iter_rows(min_row=2, max_col=2):  # 假设第一行是标题行，从第二行开始查找
                    for item in selected_items:
                        selected = item.text(0)
                    if row[0].value == selected:  # 第一列的值与selected_item匹配
                        found_value = row[1].value  # 将对应的第二列的值赋给found_value
                        break  # 找到匹配项后退出循环
                    # 现在found_value变量中包含了找到的第二列的值
                if found_value is not None:
                    print(f"Found value for {selected}: {found_value}")
                    files = os.listdir(found_value)
                    # 过滤出.msh文件
                    msh_files = [file for file in files if file.endswith('.msh')]
                    if not msh_files:
                        # 如果没有.msh文件，弹出错误窗口
                        QMessageBox.warning(self, '错误', 'No .msh files found in the directory.')
                    else:
                        # 如果有.msh文件，返回第一个.msh文件的完整路径
                        print("here", msh_files)
                        full_p = os.path.join(found_value, msh_files[0])
                        print(f"The full path to the .msh file is: {full_p}")
                        self.hide()
                        showmsh(full_p)

                else:
                    print(f"No value found for {selected}")
                    QMessageBox.warning(self, '错误', '找不到该文件地址，请重新创建!')
        self.show()




#软件首页
    #创建头部模型-选择头部模型保存路径
    def pickAshow1(self, Filepath):
        m = QtWidgets.QFileDialog.getExistingDirectory(None, "选取文件夹", "C:/")  # 起始路径
        self.ui.label_33.setText(m)
    #打开已有头部模型-选择头部模型路径
    def pickAshow2(self, Filepath):
        m = QtWidgets.QFileDialog.getExistingDirectory(None, "选取文件夹", "C:/")  # 起始路径
        self.ui.label_32.setText(m)
    #创建头部模型-选择T1文件
    def pickAshow3(self):
        filename,filetype = QtWidgets.QFileDialog.getOpenFileName(None, "选取文件", "C:/")  # 起始路径
        self.ui.label_34.setText(filename)
    # 创建头部模型-选择T2文件
    def pickAshow4(self):
        filename,filetype = QtWidgets.QFileDialog.getOpenFileName(None, "选取文件", "C:/")  # 起始路径
        self.ui.label_35.setText(filename)
    # 创建头部模型-选择dMRI文件
    def pickAshow5(self):
        filename,filetype = QtWidgets.QFileDialog.getOpenFileName(None, "选取文件", "C:/")  # 起始路径
        self.ui.label_36.setText(filename)

    #跳转至头部模型详情页面
    def Jump2Zhang(self):
        self.ui.stackedWidget_5.setCurrentIndex(0)
        # 展示Excel中数据
        filename = 'data_log.xlsx'
        full_path = os.path.join(headModule_path, filename)
        try:
            workbook = openpyxl.load_workbook(full_path)
            self.updateTreeWidget(full_path, workbook['电极仿真'], self.ui.treeWidget)
            self.updateTreeWidget(full_path, workbook['光源仿真'], self.ui.treeWidget_3)
            self.updateTreeWidget(full_path, workbook['优化配置'], self.ui.treeWidget_2)
        except Exception as e:
            QMessageBox.critical(self, 'Error', str(e))
    #跳转至优化配置页面
    def Jump2Opt(self):
        self.ui.stackedWidget_5.setCurrentIndex(3)
    #点击取消，返回到头部模型详情页面
    def back_head(self):
        global config_parameters
        self.ui.lineEdit_12.setText("")
        self.ui.label_37.setText("")
        self.ui.label_41.setText("")
        self.ui.label_46.setText("")
        self.ui.label_47.setText("")
        self.ui.label_48.setText("")
        config_parameters.update({'name':'','output_path':'','optional_goal':'','partition_input':'','ICA_input':'','TargetDot':'','AvoidDot':'','max_total_current':'','max_individual_current':'','max_active_electrodes':'','target_image_in_mni':'','target_intensity':'','target_dot_in_mni':'','avoid_dot_in_mni':''})
        self.layout().removeWidget(self.canvas)
        self.canvas.deleteLater()
        self.ui.stackedWidget_5.setCurrentIndex(0)
    #在每个头部模型文件夹下创建一个excel作为数据库使用
    def create_excel(self,path):
        excel_file_path = path+'/data_log.xlsx'
        data = {
            'name': [],
            'path': [],
            'group': []
        }
        df = pd.DataFrame(data)
        if os.path.isfile(excel_file_path):
            print('已存在该文件')
        else:
            with pd.ExcelWriter(excel_file_path, engine='openpyxl', mode='w') as writer:
                df.to_excel(writer, sheet_name='电极仿真', index=False)  # index=False 指示不写入行索引
                df.to_excel(writer, sheet_name='光源仿真', index=False)  # index=False 指示不写入行索引
                df.to_excel(writer, sheet_name='优化配置', index=False)  # index=False 指示不写入行索引
    def add2excel(self,name,path):
        global headModule_path
        # 先将Excel中原有的数据读取出来
        excel_path=headModule_path+'/data_log.xlsx'
        original_data = pd.read_excel(excel_path,sheet_name='优化配置')
        data2 = {'name': [name],
                 'path': [path],
                 'group':['default']}
        data2 = pd.DataFrame(data2)
        # 将新数据与旧数据合并起来
        save_data = original_data.append(data2)
        book = load_workbook(excel_path)
        with pd.ExcelWriter(excel_path, engine='openpyxl', mode='w') as writer:
            writer.book = book
            writer.sheets = {i.title: i for i in book.worksheets}  # 指定sheet
            save_data.to_excel(writer, sheet_name="优化配置", index=False)
    #创建头部模型
    def createHead(self):
        global create_head
        global headModule_path
        #检查T1文件是否上传，如未上传则弹窗提示
        T1_path = self.ui.label_34.text()
        subject_name = self.ui.lineEdit_4.text()
        T2_path = self.ui.label_35.text()
        dMRI_path = self.ui.label_36.text()
        head_models_folder = self.ui.label_33.text()
        if T1_path=='':
            self.hide()
            self.warning_t1.show()
        elif head_models_folder=='':
            self.hide()
            self.warning_path.show()
        else:
            # 创建头部模型，向py文件传参
            create_head.update(
                {'subject_name': subject_name, 'T1_path': T1_path, 'T2_path': T2_path, 'dMRI_path': dMRI_path,
                 'head_models_folder': head_models_folder})
            print(create_head)
            self.create_excel(head_models_folder)
            headModule_path = head_models_folder
            head_model.create_head_model(
                T1_path=create_head.get("T1_path"),
                T2_path=create_head.get("T2_path"),
                dMRI_path=create_head.get("dMRI_path"),
                subject_name=create_head.get("subject_name"),
                head_models_folder=create_head.get("head_models_folder")
            )
            self.Jump2Zhang()
    #点击“取消”按钮
    def cleanInput(self):
        self.ui.lineEdit_4.setText('')
        self.ui.label_33.setText('')
        self.ui.label_34.setText('')
        self.ui.label_35.setText('')
        self.ui.label_36.setText('')
    #直接打开头部模型文件夹时，调用此函数
    def nextPage(self):
        if self.ui.label_32.text()!='':
            global headModule_path
            self.create_excel(self.ui.label_32.text())
            headModule_path = self.ui.label_32.text()
            self.Jump2Zhang()

#优化配置页面
    #选择配置文件存储位置
    def pickAshow6(self, Filepath):
        m = QtWidgets.QFileDialog.getExistingDirectory(None, "选取文件夹", "C:/")  # 起始路径
        self.ui.label_37.setText(m)
    # 选择靶区文件路径
    def pickAshow7(self):
        filename,filetype = QtWidgets.QFileDialog.getOpenFileName(None, "选取文件", "C:/")  # 起始路径
        self.ui.label_41.setText(filename)
    # 选择靶网络文件路径
    def pickAshow8(self):
        filename,filetype = QtWidgets.QFileDialog.getOpenFileName(None, "选取文件", "C:/")  # 起始路径
        self.ui.label_46.setText(filename)
    # 叠加靶区nii文件时，需要调用的连带函数
    def update_images(self,ti_data,target_data):
        global subject_MNI
        x_idx = self.ui.horizontalSlider.value()
        y_idx = self.ui.horizontalSlider_2.value()
        z_idx = self.ui.horizontalSlider_3.value()
        # Clear previous images
        for ax in self.axs:
            ax.clear()
        # Display slices
        if subject_MNI=="subject":
            self.axs[0].imshow(ti_data[x_idx, :, :], cmap='gray', alpha=0.5)
            self.axs[0].imshow(target_data[x_idx, :, :], cmap='jet', alpha=0.5)
            self.axs[0].set_title(f'X Slice: {x_idx}')

            self.axs[1].imshow(ti_data[:, y_idx, :].T, cmap='gray', alpha=0.5)
            self.axs[1].imshow(target_data[:, y_idx, :].T, cmap='jet', alpha=0.5)
            self.axs[1].set_title(f'Y Slice: {y_idx}')

            self.axs[2].imshow(ti_data[:, :, z_idx].T, cmap='gray', alpha=0.5)
            self.axs[2].imshow(target_data[:, :, z_idx].T, cmap='jet', alpha=0.5)
            self.axs[2].set_title(f'Z Slice: {z_idx}')
        elif subject_MNI=="MNI":

            self.axs[0].imshow(ti_data[x_idx, :, :], cmap='gray', alpha=0.5)
            self.axs[0].imshow(target_data[x_idx, :, :], cmap='jet', alpha=0.5,vmin=-1.5, vmax=2)
            self.axs[0].set_title(f'X Slice: {x_idx}')

            self.axs[1].imshow(ti_data[:, y_idx, :], cmap='gray', alpha=0.5)
            self.axs[1].imshow(target_data[:, y_idx, :], cmap='jet', alpha=0.5, vmin=-1.5, vmax=2)
            self.axs[1].set_title(f'Y Slice: {y_idx}')

            self.axs[2].imshow(ti_data[:, :, z_idx], cmap='gray', alpha=0.5)
            self.axs[2].imshow(target_data[:, :, z_idx], cmap='jet', alpha=0.5, vmin=-1.5, vmax=2)
            self.axs[2].set_title(f'Z Slice: {z_idx}')

        for ax in self.axs:
            ax.axis('off')

        self.canvas.draw()  # Refresh the canvas
    #添加靶区
    def add_area(self):
        self.pickAshow7()
        self.showpicture()
    #添加靶网络
    def add_net(self):
        self.pickAshow8()
        self.showpicture()
    def showpicture(self):
        global headModule_path
        global subject_MNI
        msgBox = QMessageBox()
        if self.ui.radioButton_22.isChecked():
            target_path = self.ui.label_41.text()
        elif self.ui.radioButton_23.isChecked():
            target_path = self.ui.label_46.text()
        #给T1_subject和T1_MNI赋值
        T1_subject_path=headModule_path + '/T1.nii.gz'
        T1_MNI_path=headModule_path + '/MNI152_T1_1mm.nii.gz'
        if os.path.isfile(T1_MNI_path):
            T1_MNI=T1_MNI_path
        else:
            T1_MNI=""
        #根据T1_subject和T1_MNI的值，调用对应的叠加函数
        if T1_MNI!="":
            if nib.load(T1_subject_path).get_fdata().shape == nib.load(target_path).get_fdata().shape:
                subject_MNI = "subject"
                self.showpicture_subject()
            else:
                print(nib.load(T1_subject_path).get_fdata().shape)
                print(nib.load(target_path).get_fdata().shape)
                subject_MNI = "MNI"
                self.showpicture_MNI()
        elif T1_MNI=="":
            if nib.load(T1_subject_path).get_fdata().shape == nib.load(target_path).get_fdata().shape:
                subject_MNI = "subject"
                self.showpicture_subject()
            else:
                msgBox.setIcon(QMessageBox.Warning)
                msgBox.setText("没有与之匹配的T1文件，请检查")
                msgBox.exec_()

    #叠加subject空间靶区/靶网络nii文件时，调用此函数
    def showpicture_subject(self):
        global headModule_path
        global subject_MNI
        ti_img = nib.load(headModule_path + '/T1.nii.gz')
        if self.ui.radioButton_22.isChecked():
            target_img = nib.load(self.ui.label_41.text())
        elif self.ui.radioButton_23.isChecked():
            target_img = nib.load(self.ui.label_46.text())
        ti_data1 = ti_img.get_fdata()
        target_data1 = target_img.get_fdata()

        ti_data = np.flip(ti_data1, axis=1)  # 例如，翻转 X 轴
        target_data = np.flip(target_data1, axis=1)  # 例如，翻转 X 轴

        if ti_data.shape != target_data.shape:
            raise ValueError("两个NIfTI图像的形状不一致，请检查.")
        print(ti_data.shape)
        print(target_data.shape)

        self.ui.horizontalSlider.setMaximum(ti_data.shape[0])
        self.ui.horizontalSlider_2.setMaximum(ti_data.shape[1])
        self.ui.horizontalSlider_3.setMaximum(ti_data.shape[2])

        self.ui.horizontalSlider.setValue(round(ti_data.shape[0]/2))
        self.ui.horizontalSlider_2.setValue(round(ti_data.shape[1]/2))
        self.ui.horizontalSlider_3.setValue(round(ti_data.shape[2]/2))

        self.update_images(ti_data,target_data)
        self.ui.horizontalSlider.valueChanged.connect(lambda: self.update_images(ti_data,target_data))
        self.ui.horizontalSlider_2.valueChanged.connect(lambda: self.update_images(ti_data,target_data))
        self.ui.horizontalSlider_3.valueChanged.connect(lambda: self.update_images(ti_data,target_data))
        #plt.tight_layout()
        plt.show()
    #叠加MNI空间靶区/靶网络nii文件时，调用此函数
    def showpicture_MNI(self):
        global headModule_path
        ti_img = sitk.ReadImage(headModule_path + '/MNI152_T1_1mm.nii.gz')  # T1 加权 MRI 图像
        if self.ui.radioButton_22.isChecked():
            target_img = sitk.ReadImage(self.ui.label_41.text())
        elif self.ui.radioButton_23.isChecked():
            target_img = sitk.ReadImage(self.ui.label_46.text())
        t1_spacing = ti_img.GetSpacing()

        # 重采样分割图像，使其和 T1 图像大小一致
        resampler = sitk.ResampleImageFilter()
        resampler.SetSize(ti_img.GetSize())
        resampler.SetOutputSpacing(t1_spacing)
        resampler.SetOutputOrigin(ti_img.GetOrigin())
        resampler.SetOutputDirection(ti_img.GetDirection())
        resampler.SetDefaultPixelValue(0)  # 如果在重采样时出现空值，使用 0 填充

        # 使用线性插值进行重采样
        resampler.SetInterpolator(sitk.sitkNearestNeighbor)  # 分割图通常用邻近插值
        resampled_seg_image = resampler.Execute(target_img)

        # 将图像转换为 numpy 数组
        ti_data1 = sitk.GetArrayFromImage(ti_img)
        target_data1 = sitk.GetArrayFromImage(resampled_seg_image)
        ti_data = np.flip(ti_data1, axis=0)  # 例如，翻转 X 轴
        target_data = np.flip(target_data1, axis=0)  # 例如，翻转 X 轴
        self.ui.horizontalSlider.setMaximum(ti_data.shape[0])
        self.ui.horizontalSlider_2.setMaximum(ti_data.shape[1])
        self.ui.horizontalSlider_3.setMaximum(ti_data.shape[2])

        self.ui.horizontalSlider.setValue(round(ti_data.shape[0]/2))
        self.ui.horizontalSlider_2.setValue(round(ti_data.shape[1]/2))
        self.ui.horizontalSlider_3.setValue(round(ti_data.shape[2]/2))

        self.update_images(ti_data,target_data)
        self.ui.horizontalSlider.valueChanged.connect(lambda: self.update_images(ti_data,target_data))
        self.ui.horizontalSlider_2.valueChanged.connect(lambda: self.update_images(ti_data,target_data))
        self.ui.horizontalSlider_3.valueChanged.connect(lambda: self.update_images(ti_data,target_data))
        #plt.tight_layout()
        plt.show()
    #根据滑动条的数值，新建靶点nii文件
    def create_dot(self,a,b,c):
        global dot_flag
        def create_sphere(data, center, radius, value=1):
            """在指定位置创建一个小球。"""
            z, y, x = np.indices(data.shape)
            dist_sq = (x - center[0]) ** 2 + (y - center[1]) ** 2 + (z - center[2]) ** 2
            mask = dist_sq <= radius ** 2  # 小球的掩码
            data[mask] = value  # 设置球内的值
        # 创建一个空的3D图像数组 (例如：100x100x100)
        data = np.zeros((a, b, c), dtype=np.float32)
        # 定义要写入的小球的中心坐标和半径
        center= (self.ui.horizontalSlider_3.value(), b-self.ui.horizontalSlider_2.value(), self.ui.horizontalSlider.value())  # 中心坐标
        if dot_flag=="靶点":
            self.ui.label_47.setText(str(center))
        else:
            self.ui.label_48.setText(str(center))
        radius = 3  # 半径
        print(center)
        # 在数组中创建小球
        create_sphere(data, center, radius)

        # 创建一个 NIfTI 图像对象
        affine = np.eye(4)  # 创建单位矩阵作为仿射变换
        nii_img = nib.Nifti1Image(data, affine)

        # 保存 NIfTI 文件
        nib.save(nii_img, 'output_with_sphere.nii')

        print("小球已写入并保存为 output_with_sphere.nii")
    # 叠加靶点nii文件时，需要调用的连带函数
    def update_images2(self,ti_data,target_data):
        x_idx = self.ui.horizontalSlider.value()
        y_idx = self.ui.horizontalSlider_2.value()
        z_idx = self.ui.horizontalSlider_3.value()
        # Clear previous images
        for ax in self.axs:
            ax.clear()
        # Display slices
        self.axs[0].imshow(ti_data[x_idx, :, :], cmap='gray', alpha=0.5)
        self.axs[0].imshow(target_data[x_idx, :, :], cmap='jet', alpha=0.5)
        self.axs[0].set_title(f'X Slice: {x_idx}')

        self.axs[1].imshow(ti_data[:, y_idx, :].T, cmap='gray', alpha=0.5)
        self.axs[1].imshow(target_data[:, y_idx, :].T, cmap='jet', alpha=0.5)
        self.axs[1].set_title(f'Y Slice: {y_idx}')

        self.axs[2].imshow(ti_data[:, :, z_idx].T, cmap='gray', alpha=0.5)
        self.axs[2].imshow(target_data[:, :, z_idx].T, cmap='jet', alpha=0.5)
        self.axs[2].set_title(f'Z Slice: {z_idx}')

        for ax in self.axs:
            ax.axis('off')

        self.canvas.draw()  # Refresh the canvas
    #设置添加的是靶点还是避免点
    def set_dot_flag(self):
        global dot_flag
        dot_flag = "靶点"
        self.showpicture2()
    def set_avoid_flag(self):
        global dot_flag
        dot_flag = "避免点"
        self.showpicture2()
    #叠加靶点nii文件时，调用此函数
    def showpicture2(self):
        global headModule_path
        ti_img = nib.load(headModule_path + '/T1.nii.gz')
        ti_data1 = ti_img.get_fdata()
        ti_data = np.flip(ti_data1, axis=1)  # 例如，翻转 X 轴
        self.create_dot(ti_data.shape[0],ti_data.shape[1],ti_data.shape[2])
        target_img = nib.load('output_with_sphere.nii')
        target_data1 = target_img.get_fdata()
        target_data = np.flip(target_data1, axis=1)  # 例如，翻转 X 轴
        if ti_data.shape != target_data.shape:
            raise ValueError("两个NIfTI图像的形状不一致，请检查.")
        print(ti_data.shape)
        print(target_data.shape)

        self.ui.horizontalSlider.setMaximum(ti_data.shape[0])
        self.ui.horizontalSlider_2.setMaximum(ti_data.shape[1])
        self.ui.horizontalSlider_3.setMaximum(ti_data.shape[2])

        self.update_images2(ti_data,target_data)
        self.ui.horizontalSlider.valueChanged.connect(lambda: self.update_images2(ti_data,target_data))
        self.ui.horizontalSlider_2.valueChanged.connect(lambda: self.update_images2(ti_data,target_data))
        self.ui.horizontalSlider_3.valueChanged.connect(lambda: self.update_images2(ti_data,target_data))
        plt.show()

    #删除靶点
    def delet_dot(self):
        self.ui.label_47.setText("")
    #删除避免点
    def delet_avoid(self):
        self.ui.label_48.setText("")
    # 加载默认T1图象时的连带调用函数
    def setup_matplotlib(self):
        # Create matplotlib figure and axes
        fig = Figure(figsize=(50,5))
        axs = [fig.add_subplot(2, 2, i + 1) for i in range(3)]
        fig.tight_layout()
        return fig, axs
    #加载默认T1图象时的连带调用函数
    def update_images1(self, ti_data):
        x_idx = self.ui.horizontalSlider.value()
        y_idx = self.ui.horizontalSlider_2.value()
        z_idx = self.ui.horizontalSlider_3.value()
        # Clear previous images
        for ax in self.axs:
            ax.clear()

        # Display slices
        self.axs[0].imshow(ti_data[x_idx, :, :], cmap='gray', alpha=0.5)
        self.axs[0].set_title(f'X Slice: {x_idx}')

        self.axs[1].imshow(ti_data[:, y_idx, :].T, cmap='gray', alpha=0.5)
        self.axs[1].set_title(f'Y Slice: {y_idx}')

        self.axs[2].imshow(ti_data[:, :, z_idx].T, cmap='gray', alpha=0.5)
        self.axs[2].set_title(f'Z Slice: {z_idx}')

        for ax in self.axs:
            ax.axis('off')
        self.canvas.draw()  # Refresh the canvas
    #优化配置页面，默认加载T1图象
    def init_optional(self):
        global headModule_path
        ti_img = nib.load(headModule_path+'/T1.nii.gz')
        ti_data1 = ti_img.get_fdata()
        ti_data = np.flip(ti_data1, axis=1)  # 例如，翻转 X 轴

        self.ui.horizontalSlider.setMaximum(ti_data.shape[0])
        self.ui.horizontalSlider_2.setMaximum(ti_data.shape[1])
        self.ui.horizontalSlider_3.setMaximum(ti_data.shape[2])

        self.ui.horizontalSlider.setValue(round(ti_data.shape[0] / 2))
        self.ui.horizontalSlider_2.setValue(round(ti_data.shape[1] / 2))
        self.ui.horizontalSlider_3.setValue(round(ti_data.shape[2] / 2))

        # Set up matplotlib figure and canvas
        self.fig, self.axs = self.setup_matplotlib()
        self.canvas = FigureCanvas(self.fig)

        # Create horizontal layout in the central widget for the canvas
        layout = self.ui.verticalLayout_13
        layout.addWidget(self.canvas)  # Add the canvas to the layout

        self.update_images1(ti_data)
        self.ui.horizontalSlider.valueChanged.connect(lambda: self.update_images1(ti_data))
        self.ui.horizontalSlider_2.valueChanged.connect(lambda: self.update_images1(ti_data))
        self.ui.horizontalSlider_3.valueChanged.connect(lambda: self.update_images1(ti_data))
        # plt.tight_layout()
        plt.show()
        self.ui.radioButton_21.setChecked(True)
        self.ui.label_37.setWordWrap(True)
        self.ui.label_41.setWordWrap(True)
        self.ui.label_46.setWordWrap(True)
        self.ui.lineEdit_13.setText("0.2")
        self.ui.lineEdit_14.setText("0.002")
        self.ui.lineEdit_15.setText("0.001")
        self.ui.lineEdit_16.setText("8")
        self.Jump2Opt()
    # 当“靶点”单选框输入发生改变时，调用此函数
    def MonitorDot(self):
        if self.ui.radioButton_21.isChecked():
            self.ui.pushButton_34.hide()
            self.ui.label_41.hide()
            self.ui.pushButton_56.hide()
            self.ui.label_46.hide()
            self.ui.checkBox.hide()
        else:
            self.ui.pushButton_34.show()
            self.ui.label_41.show()
            self.ui.pushButton_56.show()
            self.ui.label_46.show()
            self.ui.checkBox.show()
    # 当“靶区”单选框输入发生改变时，调用此函数
    def MonitorArea(self):
        if self.ui.radioButton_22.isChecked():
            self.ui.pushButton_56.hide()
            self.ui.label_46.hide()
            self.ui.label_47.hide()
            self.ui.label_48.hide()
            self.ui.label_16.hide()
            self.ui.label_38.hide()
            self.ui.pushButton_9.hide()
            self.ui.pushButton_53.hide()
            self.ui.pushButton_54.hide()
            self.ui.pushButton_55.hide()
            self.ui.checkBox_2.hide()
            self.ui.checkBox_3.hide()
        else:
            self.ui.pushButton_56.show()
            self.ui.label_46.show()
            self.ui.label_47.show()
            self.ui.label_48.show()
            self.ui.label_16.show()
            self.ui.label_38.show()
            self.ui.pushButton_9.show()
            self.ui.pushButton_53.show()
            self.ui.pushButton_54.show()
            self.ui.pushButton_55.show()
            self.ui.checkBox_2.show()
            self.ui.checkBox_3.show()
    #当“靶网络”单选框输入发生改变时，调用此函数
    def MonitorNetwork(self):
        if self.ui.radioButton_23.isChecked():
            self.ui.pushButton_34.hide()
            self.ui.label_41.hide()
            self.ui.label_16.hide()
            self.ui.label_38.hide()
            self.ui.label_47.hide()
            self.ui.label_48.hide()
            self.ui.pushButton_9.hide()
            self.ui.pushButton_53.hide()
            self.ui.pushButton_54.hide()
            self.ui.pushButton_55.hide()
            self.ui.checkBox_2.hide()
            self.ui.checkBox_3.hide()
        else:
            self.ui.pushButton_34.show()
            self.ui.label_41.show()
            self.ui.label_16.show()
            self.ui.label_38.show()
            self.ui.label_47.show()
            self.ui.label_48.show()
            self.ui.pushButton_9.show()
            self.ui.pushButton_53.show()
            self.ui.pushButton_54.show()
            self.ui.pushButton_55.show()
            self.ui.checkBox_2.show()
            self.ui.checkBox_3.show()
    #点击“优化”按钮，传参给python
    def optional_show(self):
        global headModule_path
        global config_parameters
        msgBox = QMessageBox()
        name=self.ui.lineEdit_12.text()
        output_path=self.ui.label_37.text()
        partition_input=self.ui.label_41.text()
        ICA_input=self.ui.label_46.text()
        if self.ui.label_47.text()!="":
            TargetDot1 = self.ui.label_47.text().strip('()').split(',')
            TargetDot = tuple([float(TargetDot1[0]), float(TargetDot1[1]), float(TargetDot1[2])])
        if self.ui.label_48.text()!="":
            AvoidDot1 = self.ui.label_48.text().strip('()').split(',')
            AvoidDot = tuple([float(AvoidDot1[0]), float(AvoidDot1[1]), float(AvoidDot1[2])])
        max_total_current = self.ui.lineEdit_14.text()
        max_individual_current = self.ui.lineEdit_15.text()
        max_active_electrodes = self.ui.lineEdit_16.text()
        if self.ui.checkBox.isChecked():
            target_image_in_mni=True
        else:
            target_image_in_mni = False
        if self.ui.checkBox_2.isChecked():
            target_dot_in_mni=True
        else:
            target_dot_in_mni = False
        if self.ui.checkBox_3.isChecked():
            avoid_dot_in_mni=True
        else:
            avoid_dot_in_mni = False
        target_intensity=self.ui.lineEdit_13.text()
        if self.ui.radioButton_21.isChecked():
            config_parameters.update({'name': name, 'output_path': output_path, 'optional_goal': "靶点", 'TargetDot': TargetDot,
          'AvoidDot': AvoidDot,  'max_total_current': max_total_current, 'max_individual_current': max_individual_current,
          'max_active_electrodes': max_active_electrodes,'target_intensity':target_intensity,'target_dot_in_mni':target_dot_in_mni,'avoid_dot_in_mni':avoid_dot_in_mni})
            print(config_parameters)
            small_dict={'name': name, 'output_path': output_path, 'optional_goal': "靶点", 'TargetDot': TargetDot,
          'AvoidDot': AvoidDot,  'max_total_current': max_total_current, 'max_individual_current': max_individual_current,
          'max_active_electrodes': max_active_electrodes,'target_intensity':target_intensity,'target_dot_in_mni':target_dot_in_mni,'avoid_dot_in_mni':avoid_dot_in_mni}
            for value in small_dict.values():
                if value=="":
                    print(value)
                    msgBox.setIcon(QMessageBox.Warning)
                    msgBox.setText("缺少参数，请补充输入")
                    msgBox.exec_()
            files = os.listdir(headModule_path+'/mc_leadfield')
            # 过滤出.hdf5文件
            msh_files = [file for file in files if file.endswith('.hdf5')]
            if not msh_files:
                # 如果没有.hdf5文件，弹出错误窗口
                QMessageBox.warning(self, '错误', 'No .hdf5 files found in the directory.')
            else:
                # 如果有.hdf5文件，返回第一个.msh文件的完整路径
                print("here", msh_files)
            tdcs_optimize_el.run_simulation(
                ldfd_hdf=os.path.join(headModule_path + '/mc_leadfield', msh_files[0]),
                output_path=config_parameters.get("output_path"),
                subject_folder=headModule_path,

                target_coord=config_parameters.get("TargetDot"),
                target_coord_in_mni=config_parameters.get("target_dot_in_mni"),
                target_intensity=float(config_parameters.get("target_intensity")),

                avoid_coord=config_parameters.get("AvoidDot"),
                avoid_coord_in_mni =config_parameters.get("avoid_dot_in_mni"),

                max_total_current=float(config_parameters.get("max_total_current")),
                max_individual_current=float(config_parameters.get("max_individual_current")),
                max_active_electrodes=int(config_parameters.get("max_active_electrodes"))

            )
            self.add2excel(config_parameters.get("name"),config_parameters.get("output_path"))
        if self.ui.radioButton_22.isChecked():
            config_parameters.update({'name': name, 'output_path': output_path, 'optional_goal': "靶区", 'partition_input': partition_input,
           'max_total_current': max_total_current, 'max_individual_current': max_individual_current,
          'max_active_electrodes': max_active_electrodes,'target_image_in_mni':target_image_in_mni,'target_intensity':target_intensity})
            print(config_parameters)
            small_dict ={'name': name, 'output_path': output_path, 'optional_goal': "靶区", 'partition_input': partition_input,
           'max_total_current': max_total_current, 'max_individual_current': max_individual_current,
          'max_active_electrodes': max_active_electrodes,'target_image_in_mni':target_image_in_mni,'target_intensity':target_intensity}
            for value in small_dict.values():
                if value=="":
                    print(value)
                    msgBox.setIcon(QMessageBox.Warning)
                    msgBox.setText("缺少参数，请补充输入")
                    msgBox.exec_()
            files = os.listdir(headModule_path + '/mc_leadfield')
            # 过滤出.hdf5文件
            msh_files = [file for file in files if file.endswith('.hdf5')]
            if not msh_files:
                # 如果没有.hdf5文件，弹出错误窗口
                QMessageBox.warning(self, '错误', 'No .hdf5 files found in the directory.')
            else:
                # 如果有.hdf5文件，返回第一个.msh文件的完整路径
                print("here", msh_files)
            tdcs_optimize_el_network.run_simulation(
                ldfd_hdf=os.path.join(headModule_path + '/mc_leadfield', msh_files[0]),
                output_path=config_parameters.get("output_path"),
                subject_folder=headModule_path,

                target_image=config_parameters.get("partition_input"),
                target_image_in_mni=config_parameters.get("target_image_in_mni"),
                target_intensity=float(config_parameters.get("target_intensity")),

                max_total_current=float(config_parameters.get("max_total_current")),
                max_individual_current=float(config_parameters.get("max_individual_current")),
                max_active_electrodes=int(config_parameters.get("max_active_electrodes"))

            )
            self.add2excel(config_parameters.get("name"), config_parameters.get("output_path"))
        if self.ui.radioButton_23.isChecked():
            config_parameters.update({'name': name, 'output_path': output_path, 'optional_goal': "靶网络", 'ICA_input': ICA_input,
          'max_total_current': max_total_current, 'max_individual_current': max_individual_current,'max_active_electrodes': max_active_electrodes,'target_image_in_mni':target_image_in_mni,'target_intensity':target_intensity})
            print(config_parameters)
            small_dict={'name': name, 'output_path': output_path, 'optional_goal': "靶网络", 'ICA_input': ICA_input,
          'max_total_current': max_total_current, 'max_individual_current': max_individual_current,'max_active_electrodes': max_active_electrodes,'target_image_in_mni':target_image_in_mni,'target_intensity':target_intensity}
            for value in small_dict.values():
                if value=="":
                    print(value)
                    msgBox.setIcon(QMessageBox.Warning)
                    msgBox.setText("缺少参数，请补充输入")
                    msgBox.exec_()
            files = os.listdir(headModule_path + '/mc_leadfield')
            # 过滤出.hdf5文件
            msh_files = [file for file in files if file.endswith('.hdf5')]
            if not msh_files:
                # 如果没有.hdf5文件，弹出错误窗口
                QMessageBox.warning(self, '错误', 'No .hdf5 files found in the directory.')
            else:
                # 如果有.hdf5文件，返回第一个.msh文件的完整路径
                print("here", msh_files)
            tdcs_optimize_el_network.run_simulation(
                ldfd_hdf=os.path.join(headModule_path + '/mc_leadfield', msh_files[0]),
                output_path=config_parameters.get("output_path"),
                subject_folder=headModule_path,

                target_image=config_parameters.get("ICA_input"),
                target_image_in_mni=config_parameters.get("target_image_in_mni"),
                target_intensity=float(config_parameters.get("target_intensity")),

                max_total_current=float(config_parameters.get("max_total_current")),
                max_individual_current=float(config_parameters.get("max_individual_current")),
                max_active_electrodes=int(config_parameters.get("max_active_electrodes"))

            )
            self.add2excel(config_parameters.get("name"), config_parameters.get("output_path"))



if __name__ == '__main__':
    # QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    # QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)

    w = MainWindow()

    w.show()

    sys.exit(app.exec_())

    # app = QtWidgets.QApplication(sys.argv)
    # mainwindow = QtWidgets.QWidget()
    # ui = Ui_MainWindow()
    # ui.setupUi(mainwindow)
    # mainwindow.show()
    # sys.exit(app.exec_())







